Swift 排序之sort函数
2015-12-19 本文已影响4805人
槛内浊物
前言
在OC中对一个数组排序,以及字典的排序往往都是自己写一个函数去实现。swift中就不用再自己再去做这样的事了。Swift提供了sort函数,可以让数组和字典很方便的实现排序。
简单使用
降序
let a = ["2","1","3"]
let t = a.sort { (s1, s2) -> Bool in
return s1 > s2
}
print("\(t)")//打印结果:["3", "2", "1"]
升序
let a = ["2","1","3"]
let t = a.sort { (s1, s2) -> Bool in
return s1 < s2
}
print("\(t)")//打印结果:["1", "2", "3"]
但是这就完了吗?
嘿嘿,下面我们让代码进化(以下只以升序为例)
进化版
let a = ["2","1","3"]
let t = a.sort{$0<$1}
print("\(t)")//打印结果:["1","2","3"]
瞬间提升一个档次,瞬间感觉高大上,$0,$1这是什么鬼???其实在Swift中闭包参数是可以缺省的,可以直接省略参数类型和参数名,用$0代表闭包的第一个参数,$1代表闭包的第二个参数......以此类推。同时也可以省略in关键字。
但是。。。这完了吗?
嘿嘿嘿嘿嘿,下面看下究极进化
究极进化版
let a = ["2","1","3"]
let t = a.sort(<)
print("\(t)")//打印结果:["1","2","3"]
我X,代码可以省略到这种程度。你是不是已经蠢蠢欲动,想要敲一遍代码自己试验一下了。
Dictionary版
基础版
1.根据key排序
let dic = ["1":"c","3":"a","2":"b"]
let result = dic.sort { (str1, str2) -> Bool in
return str1.0 < str2.0
}
print(result)//打印结果:[("1", "c"), ("2", "b"), ("3", "a")]
2.根据value排序
let dic = ["1":"c","3":"a","2":"b"]
let result = dic.sort { (str1, str2) -> Bool in
return str1.1 < str2.1
}
print(result)//打印结果:[("1", "c"), ("2", "b"), ("3", "a")]
升级版
1.根据key排序
let dic = ["1":"a","3":"c","2":"b"]
let result = dic.sort {$0.0 < $1.0}
print(result)//打印结果:[("1", "a"), ("2", "b"), ("3", "c")]
2.根据value排序
let dic = ["1":"a","3":"c","2":"b"]
let result = dic.sort {$0.1 < $1.1}
print(result)//打印结果:[("1", "a"), ("2", "b"), ("3", "c")]
这里不能直接用">"或者"<"