let arr = ["alex","tony","bob"]
内联闭包
let arr0 = arr.sorted(by: { (s1:String,s2:String) -> Bool in
return s1 < s2
})
print("arr0 = ",arr0)
//打印结果:arr0 = ["alex", "bob", "tony"]
根据上下文推断类型 省略()、->、Bool,写成单行表达式:
let arr1 = arr.sorted(by: {s1,s2 in return s1 > s2})
print("arr1 = ",arr1)
//打印结果:arr1 = ["tony", "bob", "alex"]
单行表达式省略return:
let arr2 = arr.sorted(by: {s1,s2 in s1 < s2})
print("arr2 = ",arr2)
//打印结果:arr2 = ["alex", "bob", "tony"]
参数名称缩写:
let arr3 = arr.sorted(by: {$0 > $1})
print("arr3 = ",arr3)
//打印结果:arr3 = ["tony", "bob", "alex"]
运算符方法:
let arr4 = arr.sorted(by: <)
print("arr4 = ",arr4)
//打印结果:arr4 = ["alex", "bob", "tony"]
尾随闭包
尾随闭包是一个书写在函数括号之后的闭包表达式,函数支持将其作为最后一个参数调用,在使用尾随闭包时,你不用写出他的参数标签。
let arr5 = arr.sorted { (s1, s2) -> Bool in
s1 > s2
}
print("arr5 = ",arr5)
//打印结果:arr5 = ["tony", "bob", "alex"]
尾随闭包改写:
let arr6 = arr.sorted() {
$0 < $1
}
print("arr6 = ",arr6)
//打印结果:arr6 = ["alex", "bob", "tony"]
如果闭包是函数或者方法的唯一参数,则可以把()省略:
let arr7 = arr.sorted {
$0 > $1
}
print("arr7 = ",arr7)
//打印结果:arr7 = ["tony", "bob", "alex"]
捕获值
func makeIncrement(_ increment:Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += increment
print(runningTotal)
return runningTotal
}
return incrementer
}
let incrementByTen = makeIncrement(10)
incrementByTen() //返回的值为10
incrementByTen() //返回的值为20
incrementByTen() //返回的值为30
闭包是引用类型:
let alsoIncrementByTen = incrementByTen
alsoIncrementByTen() //返回的值为40
逃逸闭包
当一个闭包作为参数传到一个函数中,但是这个闭包在函数返回之后才被执行,称为该闭包从函数“逃逸”。当你定义接受闭包作为参数的函数时,你可以在参数名之前标注@escaping,用来指明这个闭包是允许“逃逸”出这个函数的。例如:
var completionHandlers : [() -> Void] = []
func someFunc(completionHandler:@escaping () -> Void) {
completionHandlers.append(completionHandler)
}
func funcA() {
print("abc")
}
someFunc(completionHandler: funcA) //此时funcA还未执行
completionHandlers.first?() //打印"abc"