【问题标题】:iOS Swift how to order Dictionnary by keysiOS Swift如何按键排序字典
【发布时间】: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


【解决方案1】:

字典是无序的——这是它们的本性。你只是无法对它们进行排序。但是您可以以某种方式使用数组将键和值存储为其值。

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

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

【讨论】:

    【解决方案2】:

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

    例如-

    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。

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      或在循环中

      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
      

      【讨论】:

        猜你喜欢
        • 2016-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-27
        • 2011-06-17
        相关资源
        最近更新 更多