2016-08-23 70 views
3

我正在使用完成處理程序來總結數字。我不明白的是,如果我將代碼分成兩行,執行次數將從6次變爲7次!爲什麼?爲什麼Swift遊樂場顯示錯誤執行次數?

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)' 

IMAGE enter image description here

回答

4

它表明功能/表達多少次被稱爲該行:

enter image description here

由於調用表達式(summer())在同一行上,因此它會作爲額外的操作計數。因此,6次打印+6次返回+ 1次夏季()=該行發生了13次事件。

我不確定我是否使用了正確的術語,但這是怎麼回事。

+0

它沒有顯示閉包表達式的數量。它顯示了在閉包中表達的表達式數量^ - ^()除非我誤解了某些東西...... – Fluidity

4

它只是呈現的結果:

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

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

這裏究竟算什麼? – Honey

+0

閉包的執行次數。第一個執行返回'21' – Alexander

+0

因此,在2行版本中,不是讓我們知道'1次'執行,而是彈出結果,即21? – Honey