Sort Dictionary by Key Value

后端 未结 3 1060
萌比男神i
萌比男神i 2020-11-28 14:06
let dict: [String:Int] = [\"apple\":5, \"pear\":9, \"grape\":1]

How do you sort the dictionary based on the Int value so that the outp

3条回答
  •  日久生厌
    2020-11-28 14:24

    You need to sort your dictionary values, not your keys. You can create an array of tuples from your dictionary sorting it by its values as follow:

    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
    

    To sort your dictionary using your keys

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

    To sort your dictionary using its keys and localized comparison:

    let fruitsTupleArray = fruitsDict.sorted { $0.key.localizedCompare($1.key) == .orderedAscending  }
    

提交回复
热议问题