I'm currently working my way through the Swift Programming Manual from Apple and there is this example in the book using Function Types as Return Types.
// Using a function type as the return type of another function
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards:Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
println("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
println("(currentValue)...")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
From my understanding this
let moveNearerToZero = chooseStepFunction(currentValue > 0)
calls chooseStepFunction
and passes "true" because 3 > 0. Also I understand how the following is evaluated:
return backwards ? stepBackward : stepForward
My question is how does the function stepBackward
know to use currentValue
as its input parameter? I see what is happening but I don't understand the how or why it's happening...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…