Swift Introduction | Function Literals and Closures | Closures
Now that you understand the basics of functions as values, let us use closures, a central Swift feature.
A closure lets you pass a function as an argument to another function. Because functions are values, a function can accept another function as an argument.
This may sound unfamiliar until you see an example.
func calc(num:Int)->Int {
var res = 0
for n in 0...num {
res += n
}
return res
}
func printResult(function:(num:Int)->Int, n:Int) {
print(function(num: n))
}
printResult(calc, n: 123)
This code defines two functions: calc and printResult. As in the previous example, calc returns the sum of the values from 0 through its argument. The printResult function uses a closure.
printResult receives a function and an Int value. The function type is (num:Int)->Int. When you pass calc, printResult runs it internally and prints the result.
printResult is not limited to printing the result of calc. You can pass any function that receives an Int value and returns an Int value.
Closures let you separate a process and provide it from outside a function. This is one of their main benefits.