9.16 Closures in Swift
A closure in computer science terminology generally refers to the combination of a self-contained block of code (for example a function or closure expression) and one or more variables that exist in the context surrounding that code block. Consider, for example the following Swift function:
func functionA() -> () -> Int {
var counter = 0
func functionB() -> Int {
return counter + 10
}
return functionB
}
let myClosure = functionA()
let result = myClosure()
In the above code, functionA returns a function named functionB. In actual fact functionA is returning a closure since functionB relies on the counter variable which is declared outside the functionB’s local scope. In other words, functionB is said to have captured or closed over (hence the term...