When we run the above program using playground, we get the following result:
[NO, EA, WE, SO]
Capturing Values and Reference Types
In Swift, capturing constants and variables values is done with the help of closures. It
further refers and modify the values for those constants and variables inside the closure
body even though the variables no longer exists.
Capturing constant and variable values is achieved by using nested function by writing
function with in the body of other function.
A nested function captures
Outer function arguments.
Capture constants and variables defined within the Outer function.
In Swift, when a constant or a variable is declared inside a function, reference to that
variables are also automatically created by the closure. It also provides the facility to refer
more than two variables as the same closure as follows
let decrem = calcDecrement(forDecrement: 18 )
decrem()
Here oneDecrement and Decrement variables will both point the same memory block as
closure reference.
func calcDecrement(forDecrement total: Int) - > () - > Int {
var overallDecrement = 100
func decrementer() - > Int {
overallDecrement -= total
println(overallDecrement)
return overallDecrement
}
return decrementer
}
let decrem = calcDecrement(forDecrement: 18 )
decrem()
decrem()
decrem()