iOS Swift如何通过键订购Dictionnary

时间:2016-05-05 12:21:48

标签: ios swift sorting dictionary

我正在尝试按键(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”或新的“文章”时:

print(sortedArticles)===> [110:X],[220:Y],[218:Z]

字典尚未订购:(

3 个答案:

答案 0 :(得分:6)

字典是无序的 - 这是它们的本质。你无法对它们进行排序。但是你可以以某种方式使用数组来存储键和值作为其值。

在此处了解有关他们的更多信息http://rypress.com/tutorials/objective-c/data-types/nsdictionary

实际上有一些东西可以帮助你。了解有关keysSortedByValueUsingComparator的更多信息:

答案 1 :(得分:0)

您可以直接在字典的排序方法中执行此操作,而不是使用keys数组。

例如 -

let dict = [1.0:"One",  3.0:"Three", 2.0:"Two"]
let sortedDict = dict.sort { $0.0 > $1.0 }
print(sortedDict)
// OUTPUT : [(3.0, "Three"), (2.0, "Two"), (1.0, "One")]

在这里,您要对dict进行排序并将其分配给sortedDict。

希望有所帮助。

答案 2 :(得分:0)

或循环

let dict = [1.0:"One",  3.0:"Three", 2.0:"Two"]

for (Key, Value) in dict.sort(<) {
  print("Key = \(Key), Wert =  \(Value)")
}

//Output
Key = 1.0, Wert =  One
Key = 2.0, Wert =  Two
Key = 3.0, Wert =  Three