按键排序字典 [英] Sort Dictionary by keys
问题描述
A=> Array []
Z=> Array []
D=> Array []
等。我想要它像
A=> Array []
D=> Array []
Z=>数组[]
等。
在SO上尝试了许多解决方案,但没有人为我工作。我正在使用XCode6 Beta 5,其中一些是给编译器错误,一些解决方案提供了例外。所以任何人都可以发布字典排序的工作副本。
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'
函数来获取包含键和值的排序数组,如下所示:
code> let sortedKeysAndValues = sorted(dictionary){$ 0.0 < $ 1.0
println(sortedKeysAndValues)// [(A,[1,2]),(D,[5,6]),(Z,[3,4])]
EDIT2:每月更改的Swift语法目前喜欢
let sortedKeys = Array(dictionary.keys).sort(<)// [A,D,Z]
全部已排序
已被弃用。
I want to sort a dictionary in Swift. I have a dictionary like:
"A" => Array[]
"Z" => Array[]
"D" => Array[]
etc. I want it to be like
"A" => Array[]
"D" => Array[]
"Z" => Array[]
etc.
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"]
EDIT:
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])]
EDIT2: The monthly changing Swift syntax currently prefers
let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]
The global sorted
is deprecated.
这篇关于按键排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!