Regarding the code below, I was wondering how nested functions such as stepForward, stepBackward, when they are actually called through 'moveNearerToZero(currentValue), take currentValue as their arguments.
According to the definition of the function chooseStepFunction, the return type is (Int) -> Int. Then, is it because of the parenthesis around Int that the nested functions are able to take currentValue as their arguments?
I can't undesrtand how the value of -4 of currentValue is captured in two nested functions.
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backward ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
while currentValue != 0 {
print("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
print("zero!")
currentValue = moveNearerToZero(currentValue).