I read the book quickly and came across this example of capturing the closing value.
func makeStateMachine(maxState: Int) -> StateMachineType {
var currentState: Int = 0
return {
currentState++
if currentState > maxState {
currentState = 0
}
return currentState
}
}
let bistate = makeStateMachine(1)
println(bistate());
println(bistate());
println(bistate());
println(bistate());
The output must be "1 0 1 0"
I understand how the returned block fixes the value of the local value currentState after the function is executed, but why does this value not return to 0 the next time the function is called? Is it because of the instance of the bistat constant? Or is it because currentState is initialized to 0 in bistat initialization, and the compiler reports that
var currentState: Int = 0
is ignored? I am confused by how the next line is processed after the first call.
source
share