Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...