gpt4 book ai didi

Swift - 按键降序排序字典

转载 作者:行者123 更新时间:2023-11-28 06:38:57 25 4
gpt4 key购买 nike

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

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

最佳答案

正如 ayaio 和 Martin R 所说,您的键必须是 Int 才能按照您的意愿对字典进行排序。您还应该对 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)

//returns [(key: 100, value: "Fall in (into) bucket of water caused drowning and submersion"), (key: 24, value: "Bizarre personal appearance"), (key: 12, value : "Walked into lamppost"), (key: 6, value: "Burn due to water-skis on fire"), (key: 2, value: "Bittened by turtle")].

关于Swift - 按键降序排序字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38455114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com