Swift - 按键降序排序字典

时间:2016-07-19 09:53:13

标签: swift sorting dictionary key

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

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时,它仍然不是降序。怎么会?如何通过降序值对键进行排序? (所有键都是整数)。

2 个答案:

答案 0 :(得分: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)

//返回[(键:100,值:“落入桶中,导致溺水和淹没”),,(键:24,值:“ Bizarre个人外观”),,(键:12,值:“走进路灯柱”),(键:6,值:“着火时滑水烧伤”),(键:2,值:“被乌龟咬伤”))。

答案 1 :(得分:0)

快速4和5

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

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

示例:

var dict:[String:任意] = [“ 10”:任意,“ 2”:任意,“ 20”:任意,“ 1”:任意] dictionary.keys.sorted()

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

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

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