let dict: [String:Int] = ["apple":5, "pear":9, "grape":1]
如何根据Int
值对字典进行排序,以使输出结果为:
sortedDict = ["pear":9, "apple":5, "grape":1]
当前尝试 (排序不正确):
let sortedDict = sorted(dict) { $0.1 > $1.1 }
let dict: [String:Int] = ["apple":5, "pear":9, "grape":1]
如何根据Int
值对字典进行排序,以使输出结果为:
sortedDict = ["pear":9, "apple":5, "grape":1]
let sortedDict = sorted(dict) { $0.1 > $1.1 }
Xcode 9 • Swift 4或Xcode 8 • Swift 3
let fruitsDict = ["apple": 5, "pear": 9, "grape": 1]
let fruitsTupleArray = fruitsDict.sorted{ $0.value > $1.value }
fruitsTupleArray // [(.0 "pear", .1 9), (.0 "apple", .1 5), (.0 "grape", .1 1)]
for (fruit,votes) in fruitsTupleArray {
print(fruit,votes)
}
fruitsTupleArray.first?.key // "pear"
fruitsTupleArray.first?.value // 9
使用键来对字典进行排序
let fruitsTupleArray = fruitsDict.sorted{ $0.key > $1.key }
fruitsTupleArray // [(key "pear", value 9), (key "grape", value 1), (key "apple", value 5)]
使用键和本地化比较对字典进行排序:
let fruitsTupleArray = fruitsDict.sorted { $0.key.localizedCompare($1.key) == .orderedAscending }
编辑/更新:
我们还可以扩展Sequence
协议并实现自定义排序,使用谓词进行排序,并使用键路径属性进行排序,只要它符合Comparable
:
extension Sequence {
func sorted<T: Comparable>(_ predicate: (Element) -> T, by areInIncreasingOrder: ((T,T)-> Bool) = (<)) -> [Element] {
sorted(by: { areInIncreasingOrder(predicate($0), predicate($1)) })
}
}
let sortedFruitsAscending = fruitsDict.sorted(\.value)
print(sortedFruitsAscending)
let sortedFruitsDescending = fruitsDict.sorted(\.value, by: >)
print(sortedFruitsDescending)
将打印以下内容:
[(key: "grape", value: 1), (key: "apple", value: 5), (key: "pear", value: 9)]
[(key: "pear", value: 9), (key: "apple", value: 5), (key: "grape", value: 1)]
编辑/更新:
对于 Xcode 13 或更高版本,您可以使用一种名为 KeyPathComparator
的新通用结构:
let fruitsTupleArray = fruitsDict.sorted(using: KeyPathComparator(\.value, order: .reverse))
字典不能被排序。通常,当我需要从字典中对东西进行排序时,我会单独创建一个由字典键组成的数组。
在您的情况下,可以先创建一个键的数组,通过比较它们在字典中的值来对它们进行排序。
使用 KeyValuePairs 而不是 Dictionary
"字典中键值对的顺序在变更之间是稳定的,但除此之外是不可预测的。如果您需要一个有序的键值对集合,并且不需要 Dictionary 提供的快速键查找功能,请参阅 KeyValuePairs 类型作为替代方案。" - Swift 字典
let sortedDictionary = unsortedDictionary.sorted{$0.key > $1.key}