Swift 从大到小排序 (闭包,多种写法)
let tmp = [8,5,6,4,9,7,1]
1.
func backwards(val:Int,val2:Int) -> Bool {
return val > val2
}
let reversed = tmp.sorted(by: backwards)
2.参数名称缩写
let reversed = tmp.sorted(by: {$0 > $1})
3.
let reversed = tmp.sorted(by: {(val, val2) -> Bool in
return val > val2
})
4.
let backwards = {(val:Int, val2:Int) -> Bool in
return val > val2;
}
let reversed = tmp.sorted(by: backwards)
5.运算符函数
let reversed = tmp.sorted(by: >)
6.尾随闭包(2的尾随闭包写法)
let reversed = tmp.sorted() {$0 > $1}
7.如果函数只需要闭包表达式一个参数,当您使用尾随闭包时,您甚至可以把()省略掉
let reversed = tmp.sorted {$0 > $1}
8. 3的尾随闭包写法
let reversed = tmp.sorted() {(val, val2) -> Bool in
return val > val2
}
9. 3的尾随闭包的缩略写法
let reversed = tmp.sorted {(val, val2) -> Bool in
return val > val2
}
结果:
print(reversed)
[9, 8, 7, 6, 5, 4, 1]
PS:
1 和 4 的写法不适用于尾随闭包