简体   繁体   中英

Function Types as Return Types In Swift Explanation

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...

The stepBackward function doesn't know to use currentValue in this line -- it's not called at all at this point:

return backwards ? stepBackward : stepForward

Instead, a reference to the stepBackward is returned from chooseStepFunction and assigned to moveNearerToZero . moveNearerToZero is essentially now another name for the stepBackward function that you defined earlier, so when this happens in your loop:

currentValue = moveNearerToZero(currentValue)

you are actually calling stepBackward with currentValue as the parameter.

To see this in action, add this line right after you create moveNearerToZero :

println(moveNearerToZero(10))     // prints 9, since 10 is passed to stepBackward

The chooseStepFunction(backwards:Bool) -> (Int) -> Int is returning a (function that returns int). In this way, when chooseStepFunction is executed, the function returns the actual function that should be called based on the criteria and assigns it to moveNearerToZero. This allow it to call the correct function based on currentValue later in the code.

In the first iteration, the currentValue = moveNearerToZero(currentValue) is essentially calling currentValue = stepBackward(currentValue) .

From the apple developer library:

"You can use a function type as the return type of another function. You do this by writing a complete function type immediately after the return arrow (->) of the returning function."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM