Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)->()
let closure1:Baz = { print("foo \($0)") }
let closure2:Baz = { print("bar \($0)") }

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

This fails to compile, giving the message:

Binary operator '==' cannot be applied to two '(Int)->()' operands

OK, well, how then can we compare two closures of the same type, to see if they are the same?

like image 926
CommaToast Avatar asked Jul 23 '17 22:07

CommaToast


People also ask

What are types of closures in Swift?

There are two kinds of closures: An escaping closure is a closure that's called after the function it was passed to returns. In other words, it outlives the function it was passed to. A non-escaping closure is a closure that's called within the function it was passed into, i.e. before it returns.

What is Clouser in Swift?

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

How many types of closures are there?

Some common types of closures include continuous thread closures (CT), disc top caps, child resistant (CRC) closures, pumps, and sprayers. A CT cap is your basic closure that can be easily sealed and resealed. Disc top caps allow the user to dispense product without having to remove the cap.

Why do we use closures in Swift?

Using a closure to send back data rather than returning a value from the function means Siri doesn't need to wait for the function to complete, so it can keep its user interface interactive – it won't freeze up.


1 Answers

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<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
like image 98
Alexander Avatar answered Sep 19 '22 06:09

Alexander