1
我發現下面的代碼來自internet的閉包。它基本上是計算數字範圍的總和。使用閉包?
func sum(from: Int, to: Int, f: (Int) -> (Int)) -> Int {
var sum = 0
for i in from...to {
sum += f(i)
}
return sum
}
對於調用它,我們這樣寫
sum(from: 1, to: 10) { (num) -> (Int) in
return num
}
代碼作爲環上寫着f(i)
。可誰能解釋我這是怎麼工作的?
swift中的閉包:https://iosdevcenters.blogspot.com/2016/09/how-can-i-declare-closure-in-swift.html –