let dict: [String:Int] = ["apple":5, "pear":9, "grape":1]
如何根据Int值对字典进行排序,以便输出为:
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 }