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 –