1.使用sort方法和闭包进行数组排序
sort方法返回一个数组的有序版本。(sort方法即为Swift2.0之前的sorted方法,在swift4.0之后又修改为sorted。而原来的sort方法改名为sortInPlace,用来将原数组修改成有序版本
let numbers = [12,25,1,35,27]
let numbersSorted = numbers.sorted{ (n1:Int, n2:Int) -> Bool in
return n2>n1
}
print(numbersSorted)//[1, 12, 25, 27, 35]
2.闭包可以不用指定参数类型,编译器会帮我们推断
let numbers = [12,25,1,35,27]
let numbersSorted = numbers.sorted{ (n1, n2) -> Bool in
return n2>n1
}
print(numbersSorted)//[1, 12, 25, 27, 35]
3.还可以省略参数名,直接根据数字来引用每个参数(0,1,$2......)
let numbers = [12,25,1,35,27]
let numbersSorted = numbers.sorted{
//进行从小到大的排序
return$1 > $0
}
print(numbersSorted)//[1, 12, 25, 27, 35]
4.如果闭包只包含一行代码,可以省略return关键字
let numbers = [12,25,1,35,27]
let numbersSorted = numbers.sorted{
//进行从小到大的排序
$1 > $0
}
print(numbersSorted)//[1, 12, 25, 27, 35]
5.这个换行也是可选的,所以代码可再次精简
let numbers = [12,25,1,35,27]
let numbersSorted = numbers.sorted{ $1 > $0 }
print(numbersSorted)//[1, 12, 25, 27, 35]