Regarding the capture of Swift to close

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.

+4
source share
3 answers

This is explained in the first paragraph, Capture Values :

, . , , , .

:

Swift , .

, ( ) currentState. , , ( makeStateMachine ).

+3

: -)

, , , . , , , :

func makeStateMachine(maxState: Int) -> StateMachineType { 
    // this variable is initialised when makeStateMachien is invoked
    var currentState: Int = 0

    // the function returns this closure
    return {
        // by using 'currentState' this variable is captured
        currentState++
        if currentState > maxState {
            currentState = 0 
        }
        return currentState 
    }
} 

:

let bistate = makeStateMachine(1) 

bistate , makeStateMachine.

+1

, , ...

makeStateMachine : maxState currentState. maxState 1 currentState, 1, reset currentState 0, 1. 1, 0, 1, 0, .... maxState 1, ..., maxState, 0, ..., maxState, ...

+1

All Articles