按键对字典进行排序 [英] Sort Dictionary by keys

查看:34
本文介绍了按键对字典进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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.

这篇关于按键对字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆