【问题标题】:Swift - sort dictionary descending by keySwift - 按键降序排序字典
【发布时间】:2016-11-22 03:31:29
【问题描述】:

我正在尝试按键(降序)对字典进行排序,这是我拥有的代码:

var codes = [String:String]()

codes["2"] = "Bitten by turtle"
codes["6"] = "Burn due to water-skis on fire"
codes["12"] = "Walked into lamppost"
codes["24"] = "Bizarre personal appearance"
codes["100"] = "Fall in (into) bucket of water causing drowning and submersion"


let unsortedCodeKeys = Array(codes.keys)
print(unsortedCodeKeys)

let sortedCodeKeys = unsortedCodeKeys.sort(<)

但是,当您打印 sortedCodeKeys 时,它仍然不是降序。怎么会?如何按降序对键进行排序? (所有的键都是整数)。

【问题讨论】:

  • 因为你的键是字符串,而不是整数。
  • 首先:您正在排序字符串,而不是数字"12" &lt; "2"。第二:&lt;递增顺序排序。
  • @EricD 天哪,这太尴尬了。明显地。感谢您指出。

标签: swift sorting dictionary key


【解决方案1】:

正如 ayaio 和 Martin R 所说,您的键必须是 Ints 才能根据需要对字典进行排序。您还应该对您的 sortedCodeKeys 常量进行一些小改动,如下所示:

    var codes = [Int:String]()

    codes[2] = "Bitten by turtle"
    codes[6] = "Burn due to water-skis on fire"
    codes[12] = "Walked into lamppost"
    codes[24] = "Bizarre personal appearance"
    codes[100] = "Fall in (into) bucket of water causing drowning and submersion"

    let sortedCodeKeys = codes.sorted(by: { $0.key > $1.key })
    print(sortedCodes)

// 返回 [(key: 100, value: "掉进(进入)水桶导致溺水和淹没"), (key: 24, value: "怪异的个人形象"), (key: 12, value : "走进灯柱"), (key: 6, value: "滑水板着火烧伤"), (key: 2, value: "被乌龟咬")].

【讨论】:

    【解决方案2】:

    Swift 4 和 5

    这里你的键是字符串,用于字符串键排序:

    dictionary.keys.sorted(by: {$0.localizedStandardCompare($1) == .orderedAscending})

    例子:

    var dict:[字符串:任意] = [“10”:任意,“2”:任意,“20”:任意,“1”:任意] 字典.keys.sorted()

    -> [“1”:任意,“10”:任意,“2”:任意,“20”:任意]

    dictionary.keys.sorted(by: {$0.localizedStandardCompare($1) == .orderedAscending})

    -> [“1”:任意,“2”:任意,“10”:任意,“20”:任意]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-31
      • 2020-12-10
      • 1970-01-01
      • 2021-11-27
      • 2011-06-17
      相关资源
      最近更新 更多