gpt4 book ai didi

ios - Swift:对数字字符串字典进行排序

转载 作者:行者123 更新时间:2023-11-28 13:05:22 28 4
gpt4 key购买 nike

我有一个数字字符串字典,如下所示:

let comph : [String : [String : String]] = [
"1":["title" : "first title"],
"2":["title" : "second title"],
"10": ["title" : "last title"]
]

然后当我使用 comph.sort { $0.0 < $1.0 } 对我的词典进行排序时我明白了:

let sortedComph = comph.sort { $0.0 < $1.0 }
print(sortedComph) //["1":["title" : "first title"],"10": ["title" : "last title"],"2":["title" : "second title"]]

如何对字典进行排序,以便它按数字顺序返回键?

例如:["1":["title" : "first title"],"2":["title" : "second title"],"10": ["title" : "last title"]]

谢谢

最佳答案

根据定义,Swift 中的字典是未排序的集合。如果你想维持秩序,你需要使用其他类型。

但是,如果您感兴趣的话,看起来这个人用 Swift 写了一个 OrderedDictionary:

Learning Swift: Ordered Dictionaries

或者,一个快速的 n' dirty 解决方案是将键提取到数组中,对它们进行排序,然后遍历数组并使用键进行字典查找。

关于ios - Swift:对数字字符串字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32982093/

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