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

后端 未结 2 1489
死守一世寂寞
死守一世寂寞 2020-12-07 01:12

Suppose you have two closures of type (Int)->() in Swift 3 and test to see if they are the same as each other:

typealias Baz = (Int)->()
l         


        
2条回答
  •  攒了一身酷
    2020-12-07 01:31

    In the case where you want to track your own closures, uses them as Dictionary keys, etc., you can use something like this:

    struct TaggedClosure: 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
    

提交回复
热议问题