闭包 Closure
闭包的基本使用与简写
语法优化
var myClosure:() -> Void = {
print("Hello world")
}
myClosure()
var...= {
(a,b) in //闭包简写,类型自动推导 可以根据参数推断
return a*b
}
mySecondClosure = {
(a,b) in //进一步闭包简写...省略参数列表 (a, b)和 关键字 in
}
闭包应用
排序
var arr:[Int] = [1,3,5,6,7,2,4,6,8]
arr.sorted() //[1, 2, 3, 4, 5, 6...compactMap : 解包->展开并合并
}
//reduce
var arr5 = [0,1,2]
var sum = arr5.reduce(0) {
return $0 + $1 //3
}
闭包作为函数参数...(a:Int,b:Int) in
a * b
}
handler(2, 3, operation: multipyClosure) //将闭包作为参数传递
捕获
闭包可以从上下文环境中捕获常量