【发布时间】:2020-07-25 06:18:48
【问题描述】:
我正在为嵌套函数尝试以下示例,但出现意外行为:
func chooseStepFunction(value: Int, backward: Bool) -> (Int) -> Int {
print("Current value: \(value)")
func stepForward(input: Int) -> Int {
print("plus from \(input)");
return input + 1
}
func stepBackward(input: Int) -> Int {
print("minus from \(input)");
return input - 1
}
return backward ? stepBackward : stepForward
}
var currentValue = 4
let moveNearerToZero = chooseStepFunction(value: currentValue, backward: currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != -2 {
print("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
我尝试使用向后和向前嵌套函数,但得到以下结果:
Current value: 4
4...
minus from 4
3...
minus from 3
2...
minus from 2
1...
minus from 1
0...
minus from 0
-1...
minus from -1
就像,每次我修改currentValue 和每次我调用chooseStepFunction 但在控制台中chooseStepFunction 函数内的currentValue 只执行一次,但while 循环内的currentValue 正在执行evrytime 那么为什么chooseStepFunction 正在跳过打印值。在我看来,预期的结果将是:
Current value: 4
4...
minus from 4
3...
minus from 3
2...
minus from 2
1...
minus from 1
0...
plus from 0
1...
minus from 1
0...
plus from 0
1...
minus from 1
0...
..........
这将是一个无限循环,但为什么它工作正常? 完全没看懂?
【问题讨论】:
标签: swift5 swift-playground nested-function