Ios 函数类型作为Swift解释中的返回类型
我目前正在阅读苹果公司的Swift编程手册,书中有一个例子,使用函数类型作为返回类型Ios 函数类型作为Swift解释中的返回类型,ios,swift,Ios,Swift,我目前正在阅读苹果公司的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 chooseSte
// 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>0。我还了解如何评估以下各项:
return backwards ? stepBackward : stepForward
我的问题是函数
step backward
如何知道使用currentValue
作为其输入参数?我看到发生了什么,但我不理解它是如何发生的或为什么发生的…函数不知道在这行中使用currentValue
,此时根本不调用它:
return backwards ? stepBackward : stepForward
相反,从chooseStepFunction
返回对后退
的引用,并将其分配给moveNearerToZero
moveNearerToZero
现在本质上是您先前定义的stepfackup
函数的另一个名称,因此当循环中发生这种情况时:
currentValue = moveNearerToZero(currentValue)
实际上,您正在使用currentValue
作为参数调用step backward
要查看此操作,请在创建moveNearerToZero
后添加此行:
println(moveNearerToZero(10)) // prints 9, since 10 is passed to stepBackward
chooseStepFunction(向后:Bool)->(Int)->Int
正在返回一个(返回Int的函数)。这样,当执行chooseStepFunction
时,该函数返回应根据条件调用的实际函数,并将其分配给MoveNearTozero。这允许它根据代码后面的currentValue
调用正确的函数
在第一次迭代中,currentValue=moveNearerToZero(currentValue)
实质上调用的是currentValue=stepfackup(currentValue)
从apple开发者库:
“您可以使用一个函数类型作为另一个函数的返回类型。您可以通过在返回函数的返回箭头(->)之后立即编写一个完整的函数类型来完成此操作。”我现在明白了。非常感谢。这个练习让我的大脑处于一个“无休止的循环”中。在我有限的经验中,我很难把我的脑袋绕到像这样有用的地方。从可读性的角度来看,它似乎有点复杂。这是一种常见的做法吗?在本例中,当您传回一个或另一个现有函数时,这种情况可能不会经常发生。它在传回闭包时非常有用,闭包封装了来自其周围上下文的值。我想这就是你的下一章