【问题标题】:Nested function unexpected behaviour in Swift?Swift中的嵌套函数意外行为?
【发布时间】: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


    【解决方案1】:

    这一行:

    let moveNearerToZero = chooseStepFunction(value: currentValue, backward: currentValue > 0)
    

    只运行一次,因为它在循环之外。所以分支backward ? stepBackward : stepForward 只运行一次。代码选择了stepBackward 一次,以后再也没有。

    let someName = someExpression 并不意味着“从现在开始,每次我说someName,评估someExpression”。它的意思是“评估someExpression,并将结果放入名为someName的常量中”。

    要实现您想要的,您可以将chooseStepFunction 调用移动到循环中:

    while currentValue != -2 {
        print("\(currentValue)... ")
        let moveNearerToZero = chooseStepFunction(value: currentValue, backward: currentValue > 0)
        currentValue = moveNearerToZero(currentValue)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      相关资源
      最近更新 更多