按键对字典进行排序
我想在 Swift 中对字典进行排序.我有一本像这样的字典:
I want to sort a dictionary in Swift. I have a dictionary like:
"A" => Array[]
"Z" => Array[]
"D" => Array[]
等等.我希望它像
"A" => Array[]
"D" => Array[]
"Z" => Array[]
等
我在 SO 上尝试了很多解决方案,但没有人为我工作.我正在使用 XCode6 Beta 5,其中一些给出编译器错误,一些解决方案给出异常.所以任何人都可以发布字典排序的工作副本.
I have tried many solutions on SO but no one worked for me. I am using XCode6 Beta 5 and on it some are giving compiler error and some solutions are giving exceptions. So anyone who can post the working copy of dictionary sorting.
let dictionary = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]
let sortedKeys = Array(dictionary.keys).sorted(<) // ["A", "D", "Z"]
上述代码中的排序数组仅包含键,而必须从原始字典中检索值.但是,'Dictionary'
也是 (key, value) 对的 'CollectionType'
,我们可以使用全局的 'sorted'
函数来得到一个包含键和值的排序数组,如下所示:
The sorted array from the above code contains keys only, while values have to be retrieved from the original dictionary. However, 'Dictionary'
is also a 'CollectionType'
of (key, value) pairs and we can use the global 'sorted'
function to get a sorted array containg both keys and values, like this:
let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }
println(sortedKeysAndValues) // [(A, [1, 2]), (D, [5, 6]), (Z, [3, 4])]
目前更喜欢每月更改的 Swift 语法
The monthly changing Swift syntax currently prefers
let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]
不推荐使用全局 sorted
.