Swift Tips & Tricks: Using Functions as Parameters in Swift
Suppose you have a function that returns the double of any integer that it takes.
func doubleOfNumber(number: Int) -> Int {
return number * 2
}
And you want to double every Int in an array. You might want to do this:
[3, 1, 2, 4].map {
return doubleOfNumber($0)
}
// Returns [6, 2, 4, 8]
Now the map function in this case takes a closure that takes an Int and returns an Int. Just like our function doubleOfNumber.
We can actually use this function as a parameter instead of providing the closure ourselves. Like this:
[3, 1, 2, 4].map(doubleOfNumber)
// Returns [6, 2, 4, 8]
It gets better. Now suppose you want to convert these Ints to Strings:
[3, 1, 2, 4].map {
return String($0)
}
// Returns ["3", "1", "2", "4"]
Since String.init is itself a function, you can do this:
[3, 1, 2, 4].map(String.init)
You can even do this:
[3, 1, 2, 4].sort(<)
You can do very cool and actually practical things with Swift if you know where to look.
