Dershowitz123 Dershowitz123 - 1 year ago 49
iOS Question

What's this type of Closure supposed to mean and how does it work?

Got it from Here

The Ultimate Closure
Finally, for the ultra parsimonious there is the following, without a byte wasted.

let testEquality9 : (Int, Int) -> Bool = (==)

Answer Source

Functions decalred with the func keyword are just closures with names. == is an example of one such named function. It takes 2 Int arguements, and returns a Bool telling you if they're equal. Its type is (Int, Int) -> Bool

testEquality9 is a closure, with the type (Int, Int) -> Bool. To it, the closure of the == function is assigned.

It can be called like this:

testEquality9(1, 2) // false
testEquality9(1, 1) // true

The key thing to draw from this is that functions are really just closures, so they can be used everywhere closures can be used.

For example, if you wanted to sort an array of Ints, you could use:

let ints = [3, 1, 4, 2]
let sorted = ints.sort{$0 < $1}

The sort(_:) method takes a closure that's of type (Int, Int) -> Bool. Our closure {$0 < $1} takes 2 Int params, and returns a Bool. So it fits that signiture.

However, we can make this code shorter. Because the < operator's function already has type (Int, Int) -> Bool, we can write this:

let sorted = ints.sort(<)

This passes the function (named closure) < in directly, without explicitly making our own closure to wrap around it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download