【问题标题】:Why does Swift playground shows wrong number of executions?为什么 Swift Playground 显示错误的执行次数?
【发布时间】:2016-12-30 17:58:00
【问题描述】:

我正在使用完成处理程序来总结数字。我不明白的是,如果我将代码分成两行,执行次数将从 6 变为 7!为什么?

 func summer (from : Int, to: Int, handler: (Int) -> (Int)) -> Int {
        var sum = 0
        for i in from...to {
            sum += handler(i)
        }
        return sum

}

summer(1, to:6){ //Shows '21'
    return $0} // shows '(6 times)'


// Same code, but in 1 line
summer(1, to:6){return $0} // shows '(7 times)'

图片

【问题讨论】:

    标签: swift swift-playground


    【解决方案1】:

    它显示了在该行上调用了多少次函数/表达式:

    由于调用表达式summer() 在同一行,它被视为额外操作。因此,6 prints + 6 returns + 1 summer() = 该行发生了 13 次事情。

    【讨论】:

    • 它没有显示闭包表达式的数量.. 它显示了闭包中表达的表达式数量 ^-^() 除非我在这里弄错了......
    【解决方案2】:

    这只是演示的结果:

    21 //the result from the first time
    (6 times) //the other 6 times
    
    (7times) //all 7 times, including the 21 one.
    

    【讨论】:

    • 这里到底算什么?
    • 闭包的执行次数。这些处决中的第一个返回了21
    • 所以在 2 行版本中,它不会让我们知道“1 次”执行,它只会弹出结果,即 21?
    • 是的,如果一段代码只运行一次,它会给你实际值而不是它运行的次数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    相关资源
    最近更新 更多