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!")
Functions in Swift are first class citizens. This means that functions can be passed around or stored like a variable, just like any other swift type.
Anything that follows the first ->
is the type being returned by that method. In this case chooseStepFunction
returns another method that takes one parameter (Int) and returns one value (Int). The parenthesis around the first Int, mean that it's an input parameter.
With that in mind, moveNearerToZero
is function that takes one Int and returns another Int. To call that method, you then simply do moveNearerToZero(1)
and so on.
I highly recommend you read Apple's section on functions to better understand how functions can be used or passed around. https://docs.swift.org/swift-book/LanguageGuide/Functions.html