Swift-sort排序函数

前言

在OC中对一个数组排序,以及字典的排序往往都是自己写一个函数去实现。swift中就不用再自己再去做这样的事了。Swift提供了sort函数,可以让数组和字典很方便的实现排序。

简单使用

降序

let a = ["2","1","3"] let i = a.sort { (s1, s2) -> Bool in return s1 > s2} print("\(t)")//打印结果:["3","2","1"]

升序

let a = ["2","1","3"] let i = a.sort { (s1, s2) -> Boolin return s1 < s2} print("\(i)")//打印结果:["1","2","3"]

优化版

let a = ["2","1","3"] let i = a.sort{$0<$1} print("\(i)")//打印结果:["1","2","3"]

在Swift中闭包参数是可以缺省的,可以根据类型推断直接省略参数类型和参数名,用$0代表闭包的第一个参数,$1代表闭包的第二个参数......以此类推。同时也可以省略in关键字。

最简版

let a = ["2","1","3"] let i = a.sort(<) print("\(i)")//打印结果:["1","2","3"]

推荐阅读更多精彩内容