按键值排序字典

Oni*_*han 6 sorting swift

let dict: [String:Int] = ["apple":5, "pear":9, "grape":1]
Run Code Online (Sandbox Code Playgroud)

如何根据Int值对字典进行排序,以便输出为:

sortedDict = ["pear":9, "apple":5, "grape":1]
Run Code Online (Sandbox Code Playgroud)

当前尝试(未正确排序):

let sortedDict = sorted(dict) { $0.1 > $1.1 } 
Run Code Online (Sandbox Code Playgroud)

Leo*_*bus 23

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

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
Run Code Online (Sandbox Code Playgroud)

使用键对字典进行排序

let fruitsTupleArray = fruitsDict.sorted{ $0.key > $1.key }
fruitsTupleArray  // [(key "pear", value 9), (key "grape", value 1), (key "apple", value 5)]
Run Code Online (Sandbox Code Playgroud)

要使用键和本地化比较对字典进行排序:

let fruitsTupleArray = fruitsDict.sorted { $0.key.localizedCompare($1.key) == .orderedAscending  }
Run Code Online (Sandbox Code Playgroud)