You need to sort the dictionary values, not the keys. You can create an array of tuples from your dictionary by sorting it by its values ββas follows:
Xcode 9 β’ Swift 4 or 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
Sorting a dictionary using keys
let fruitsTupleArray = fruitsDict.sorted{ $0.key > $1.key } fruitsTupleArray // [(key "pear", value 9), (key "grape", value 1), (key "apple", value 5)]
Sorting a dictionary using its keys and localized comparison:
let fruitsTupleArray = fruitsDict.sorted { $0.key.localizedCompare($1.key) == .orderedAscending }
Leo Dabus Jul 21 '15 at 1:20 2015-07-21 01:20
source share