Swift对字符串的排序

时间:2022-06-01 21:57:08

主要是使用sorted函数,自己提供排序规则,或者自己重载< 或者 >

1.sorted对数组内的字符串升序

 

1 var name2 : [String] = ["Alice","Mike","Bob","May","Cake"]
2 
3 name2 = name2.sorted({name1 , name2 in
4 
5     return name1.localizedStandardCompare(name2) == NSComparisonResult.OrderedAscending
6 
7 })
8 
9 name2

输出结果:

["Alice", "Bob", "Cake", "May", "Mike"]

NSComparisonResult.OrderedDescending降序

2.重载 <

1 var names : [String] = ["Alice","Mike","Bob","May","Cake"]
2 names = names.sorted({$0 < $1})
3 
4 names
5 
6 func < (lhs: String, rhs:String) -> Bool {
7     return lhs.localizedStandardCompare(rhs) == NSComparisonResult.OrderedAscending
8 }

输出:["Alice", "Bob", "Cake", "May", "Mike"]

也可以重载 > 降序,修改NSCompareResult即可.