how I can pass compare operators to function and then using it?
Hello, guys. Anyone knows, how I can pass compare operators to function and then using it? I'm a Python developer which just start to learn Swift. In Python, we have operator module, which have all compare operators as a functions. E. g.:
import operatorBut I can't find similar in Swift. Thank you in advance!
def compare(a, b, op):
return op(a, b)
print(compare(1, 2, operator.eq))
No any search results
You already invited:
2 Answers
BenchR267
Upvotes from: Travelmike
func compare<T: Equatable>(a: T, b: T, op: (T, T) -> Bool) -> Bool {
operators are just functions, so == is an infix operator which takes 2 parameters and returns a boolean. the two values need to conform to the protocol Equatable from stdlibreturn op(a, b)
}
let same = compare(a: 4, b: 4, op: ==)
DrJackilD
Upvotes from:
func ==(left: MyClass, right:MyClass) -> Bool {
If you really want to do it the same way as you would in Python, you could do it like this, but because Swift is statically typed, you’ll notice that you have to write a slew of comparison functions for each type of object you’re interested in.if left.someValue == right.someValue {
return true
} else {
return false
}
}
let testObject1 = MyClass()
let testObject2 = MyClass()
print( testObject1 == testObject2 )
func compare(a:Int, b:Int, comparisonFunction:(Int, Int)->Bool) -> Bool{
return comparisonFunction(a,b)
}
func myComparisonFunction(x:Int, y:Int) -> Bool {
return x == y
}
let test = compare(a: 5, b: 5, comparisonFunction: myComparisonFunction)
print(test)