In Swift 3, what is a way to compare two closures?

Suppose you have two type closures (Int)->()in Swift 3 and check if they are the same:

typealias Baz = (Int)->()
let closure1:Baz = { print("foo \($0)") }
let closure2:Baz = { print("bar \($0)") }

if(closure1 == closure2) {
    print("equal")
}

This cannot be compiled by specifying the message:

The binary operator '==' cannot be applied to two operands '(Int) β†’ ()'

Okay, okay, how then can we compare two closures of the same type to make sure they are the same?

+4
source share
2 answers

I am sure there is no way to determine if two closures are equal.

, . . ( , , . , . , .)

, === , , , Playground.

Playground execution failed: error: MyPlayground.playground:1:20: error: cannot check reference equality of functions; operands here have types '(Int) ->  ()' and '(Int) -> ()'
let bar = closure1 === closure2
          ~~~~~~~~ ^   ~~~~~~~~

, , , , , . - , , , . , , , , .

, , .

func giveMeClosure(aString: String) -> () -> String
{
     return { "returning " + aString }
}

let closure1 = giveMeClosure(aString: "foo")
let closure2 = giveMeClosure(aString: "bar")

closure1 closure2 ?

print(closure1()) // prints "returning foo"
print(closure2()) // prints "returning bar"

, . , , , ,

func giveMeACount(aString: String) -> () -> Int
{
    return { aString.characters.count }
}

let closure3 = giveMeACount(aString: "foo")
let closure4 = giveMeACount(aString: "bar")

print(closure3()) // prints 3
print(closure4()) // prints 3

-, . - , , Apple . , , .

+5

, , .., - :

struct TaggedClosure<P, R>: Equatable, Hashable {
    let id: Int
    let closure: (P) -> R

    static func == (lhs: TaggedClosure, rhs: TaggedClosure) -> Bool {
        return lhs.id == rhs.id
    }

    var hashValue: Int { return id }
}

let a = TaggedClosure(id: 1) { print("foo") }
let b = TaggedClosure(id: 1) { print("foo") }
let c = TaggedClosure(id: 2) { print("bar") }

print("a == b:", a == b) // => true
print("a == c:", a == c) // => false
print("b == c:", b == c) // => false
+1

Source: https://habr.com/ru/post/1682081/


All Articles