为什么Swift游乐场显示错误的执行次数?

时间:2016-08-23 19:15:54

标签: swift swift-playground

我正在使用完成处理程序来总结数字。我不明白的是,如果我用2行破解我的代码,执行次数将从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)'

图片 enter image description here

2 个答案:

答案 0 :(得分:4)

这仅仅是演示的结果:

21 //the result from the first time
(6 times) //the other 6 times

(7times) //all 7 times, including the 21 one.

答案 1 :(得分:4)

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

enter image description here

因为调用表达式(summer())在同一行上,所以它被视为一个额外的操作。因此,6次打印+ 6次返回+ 1次夏季()= 13次在该行上发生的事情。

我不确定我是否使用了正确的术语,但这就是正在发生的事情。