【发布时间】: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" < "2"。第二:<按递增顺序排序。 -
@EricD 天哪,这太尴尬了。明显地。感谢您指出。
标签: swift sorting dictionary key