Just some notes on Swift closures

The most common used example to illustrate Closures is the adder as follow:

let adder: (Int, Int) -> Int = {
(a, b) in
return a + b
}
print(adder(2,3)) //5
print(adder(2,4)) //6

http://swiftlang.ng.bluemix.net/#/repl/5843cb0db4fa285b44371957

Let’s write it again in a more concise way:

let adder: (Int, Int) -> Int = {
$0 + $1
}
print(adder(2,3)) //5
print(adder(2,4)) //6

http://swiftlang.ng.bluemix.net/#/repl/5843cb56b4fa285b44371958

But let’s say we also have subtracter and multiplier we want to have a run closure, so that we can do this:

print(run(2, 3, adder))       //5
print(run(2, 3, subtracter)) //-1
print(run(2, 3, multiplier)) //6

My first attempt was to write the run function as follow:

func run(_ a: Int, _ b: Int, _ op: (Int, Int) -> Int) -> Int {
return op(a, b)
}

http://swiftlang.ng.bluemix.net/#/repl/5843cbeeb4fa285b44371959

That is not very concise and in addition I said I wanted a run closure, not a function. So here is my run closure:

let run: (Int, Int, (Int, Int) -> Int) -> Int = {
$2($0, $1)
}

http://swiftlang.ng.bluemix.net/#/repl/5843cc3ab4fa285b4437195a

But if I don’t need to store the adder, subtracter and multiplier closures in a variable, I can just do on the fly as follow:

let run: (Int, Int, (Int, Int) -> Int) -> Int = {
$2($0, $1)
}
print(run(2, 3, {$0 + $1})) //5
print(run(2, 3, {$0 - $1})) //-1
print(run(2, 3, {$0 * $1})) //6

Update:

It’s getting even cooler. After reading more about the “Operator Methods” section the Swift guide, it becomes apparent that the code above can be made even more concise. In Swift, the Int data type overloads the + operator as method that takes 2 parameters of type Int and returns a value of type Int. This matches the signature of the closure that is the third argument (which is referenced by $2) of the run closure. So Swift can make this inference. We can end up with this code:

let run: (Int, Int, (Int, Int) -> Int) -> Int = {
$2($0, $1)
}
print(run(2, 3, +)) //5
print(run(2, 3, -)) //-1
print(run(2, 3, *)) //6

http://swiftlang.ng.bluemix.net/#/repl/58443921b4fa285b44371969

Written by

Driven by passion and patience. Read my shorter posts https://dev.to/codeprototype (possibly duplicated from here but not always)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store