【发布时间】:2016-08-31 05:40:24
【问题描述】:
我正在尝试按键(The Double)订购 [Double : Article] 的字典。
我已经尝试了一切,现在我有以下代码:
// getting an array of sorted keys
let articlesKeys = articles.keys.sort{$0 > $1}
var sortedArticles = [Double:Article]()
// trying to fill the new dictionary in a descending keys order
for key in articlesKeys
{
sortedArticles[key] = articles[key]
}
// replacing the old dictionary (articles)
// with the new and ordered one (sortedArticles)
articles.removeAll()
articles = sortedArticles
问题是“articleKeys”是有序的
print(articleKeys) ===> [220, 218, 110]
但是当我打印出“sortedArticles”或新的“articles”时:
print(sortedArticles) ===> [110: X], [220: Y], [218: Z]
字典还没有排序:(
【问题讨论】:
-
如果订购了 articleKeys,您是否尝试过使用 reverse() 功能? articleKeys = articleKeys.reverse() print(articlesKeys)
-
字典是一个无序的集合,它不能像你想要的那样排序。
-
是的,你是对的,但我们可以使用包含字典键的有序数组,并从中获取键值,然后从字典中逐个对象..
-
谢谢@AlexKosyakov,我会这样做的
标签: ios swift sorting dictionary