函数类型作为返回类型在Swift解释中

时间:2014-08-14 14:17:18

标签: ios swift

我目前正在使用Apple的Swift编程手册,本书中的这个例子使用函数类型作为返回类型。

// 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!")

从我的理解

let moveNearerToZero = chooseStepFunction(currentValue > 0)

调用chooseStepFunction并传递" true"因为3>我还了解如何评估以下内容:

return backwards ? stepBackward : stepForward

我的问题是stepBackward函数如何知道使用currentValue作为输入参数?我知道发生了什么,但我不明白它发生的方式或原因...

2 个答案:

答案 0 :(得分:2)

stepBackward函数不知道在这一行中使用currentValue - 此时根本没有调用它:

return backwards ? stepBackward : stepForward

而是从stepBackward返回对chooseStepFunction的引用,并将其分配给moveNearerToZeromoveNearerToZero现在基本上是您之前定义的stepBackward函数的另一个名称,因此当您在循环中发生这种情况时:

currentValue = moveNearerToZero(currentValue)

您实际上是以stepBackward作为参数调用currentValue

要查看此操作,请在创建moveNearerToZero后立即添加此行:

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

答案 1 :(得分:1)

chooseStepFunction(backwards:Bool) -> (Int) -> Int返回一个(返回int的函数)。这样,当执行chooseStepFunction时,函数返回应根据条件调用的实际函数,并将其分配给moveNearerToZero。这允许它稍后在代码中基于currentValue调用正确的函数。

在第一次迭代中,currentValue = moveNearerToZero(currentValue)基本上是调用currentValue = stepBackward(currentValue)

来自apple developer库:

“您可以使用函数类型作为另一个函数的返回类型。您可以通过在返回函数的返回箭头( - >)之后立即编写完整的函数类型来执行此操作。”

相关问题