简单的实现swift中字典和数组内部排序问题,不用再单独写一个算法来实现排序了,简单快捷~
1.数组元素从小到大排序(根据元素数值大小)
let arrNumber = ["2","4","9","1","3"]
let sortedArrNumber = arrNumber.sorted{ (k1:String, k2:String) -> Boolin
return Int(k1)!
}
print(sortedArrNumber)//["1", "2", "3", "4", "9”]
2.数组元素从小到大排序(根据字母)
let arrLetter = ["g","a","ij","if","d"]
let sortedArrLetter =arrLetter.sorted{ (k1, k2) -> Boolin
return k1
}
print(sortedArrLetter)//["a", "d", "g", "if", "ij"]
3.字典键值对排序(根据key数值大小排序)
let dicKey = [
"6":"six",
"10":"ten",
"8":"eight",
"0":"zero",
"5":"five"
]
let sortedDicKey = dicKey.sorted{ (k1, k2) ->Boolin
return Int(k1.key)!
}
print(sortedDicKey)//[("0", "zero"), ("5", "five"), ("6", "six"), ("8", "eight"), ("10", "ten")]
4.取字典中的键排序
let sortedKeys = dicKey.keys.sorted{ (k1, k2) ->Boolin
return Int(k1)!
}
print(sortedKeys)//["0", "5", "6", "8", "10"]