作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试按键(降序)对字典进行排序,这是我的代码:
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/
我是一名优秀的程序员,十分优秀!