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