一尘不染

按键值对字典排序

swift

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 }

阅读 386

收藏
2020-07-07

共1个答案

一尘不染

您需要对字典值而不是键进行排序。您可以从字典中创建一个元组数组,按其值对它进行排序,如下所示:

Xcode 9•Swift 4Xcode 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  }
2020-07-07