【发布时间】:2017-08-22 19:43:45
【问题描述】:
我试图快速理解关闭。我有以下快速实现:
func whereToGo (ahead:Bool) -> (Int) -> Int{
func goAhead(input:Int) ->Int{
return input + 1 }
func goBack(input:Int) ->Int{
return input - 1 }
return ahead ? goAhead : goBack
}
var stepsToHome = -10
let goHome = whereToGo(ahead: stepsToHome < 0)
while stepsToHome != 0 {
print("steps to home: \(abs(stepsToHome))")
stepsToHome = goHome(stepsToHome)
}
实现的输出如下:
steps to home: 10
steps to home: 9
steps to home: 8
steps to home: 7
steps to home: 6
steps to home: 5
steps to home: 4
steps to home: 3
steps to home: 2
steps to home: 1
我的问题如下:
-
为什么只执行这个闭包:
func goAhead(input:Int) ->Int{ return input + 1 } -
为什么这一行不采用变量值:
提前返回? goAhead : 后退
非常感谢您帮助我了解快速关闭的工作原理。
【问题讨论】:
-
您的问题更多地涉及嵌套函数,它们是闭包的特例。
-
正如苹果文档所说-:嵌套函数是具有名称的闭包,可以从其封闭函数中捕获值。developer.apple.com/library/content/documentation/Swift/…