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 operator

def compare(a, b, op):
return op(a, b)

print(compare(1, 2, operator.eq))
But I can't find similar in Swift. Thank you in advance!
You already invited:

BenchR267

Upvotes from: Travelmike

func compare<T: Equatable>(a: T, b: T, op: (T, T) -> Bool) -> Bool {
return op(a, b)
}

let same = compare(a: 4, b: 4, op: ==)
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 stdlib

DrJackilD

Upvotes from:

Swift supports defining of custom operators and overriding of common operators. In your case, you might consider overriding the standard compare operator == for whatever use case you have in mind. For example, the code snippet you use might look something like this.
func ==(left: MyClass, right:MyClass) -> Bool {
if left.someValue == right.someValue {
return true
} else {
return false
}
}

let testObject1 = MyClass()
let testObject2 = MyClass()

print( testObject1 == testObject2 )
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.
 
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)

If you wanna answer this question please Login or Register