【问题标题】:swift Dictionary problem where it needs to be ordered by the key需要按键排序的快速字典问题
【发布时间】:2021-10-01 23:52:36
【问题描述】:

我有一个问题,我可以对字典进行排序,但结果很奇怪。


  class MyModel {
     var dict = [Date: Int]()
    ...
  }
  let sortDict = dict.sorted { (first, second) -> Bool in
      return first.key > second.key
    }
    dictDatePlacesCount = sortDict[0]

问题是我得到一个语法错误

Cannot assign value of type 'Dictionary<Date, Int>.Element' (aka '(key: Date, value: Int)') to type '[Date : Int]'

问题是我不能使用这种按日期降序排序的规则创建自定义字典?

我确实探索并找到了 OrderedDictionary,但它似乎是一个外部包?

【问题讨论】:

  • 似乎dictDatePlacesCount被声明为字典[Date: Int]而不是字典元素(键值对)(Date, Int)
  • 是的,OrderedDictionary 来自一个名为 Swift Collections 的外部包。如果你真的想要 Dictionary 作为你的结果类型,你肯定应该使用类似的东西。您现在尝试调用的sorted 函数不会返回Dictionary,它会返回一个Array,其中包含一个代表keysvalues 的元组:developer.apple.com/documentation/swift/dictionary/…

标签: swift ordereddictionary


【解决方案1】:

正如 jnpdx 所说,Dictionary 方法 sorted() 返回一个类型为 (Key, Value) 的元组数组(因此在您的情况下为 (Date, Int)。)

Swift 标准库没有有序字典。同样,正如 jnpx 所提到的,有像官方Swift Collections 这样提供有序字典的框架/库。您可能想使用其中之一。

或者,您可以对字典中的键进行排序,并使用它们来索引您的内容。

【讨论】:

  • 公平地说,Swift Collections 并不是真正的“第三方”。它是“stdlib 的舞台”。它并没有做出 stdlib 的所有 ABI 承诺,但它不仅仅是 GitHub 上的一些随机代码。
  • 我稍微修改了措辞,因为声明“在 Swift 中没有排序字典之类的东西”是错误的,因为官方的 Swift Collections 包肯定算作“在 swift 中”。
  • 更好的单词选择。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-01
  • 2018-01-31
  • 2019-10-16
  • 2020-11-12
  • 2020-02-09
  • 2021-11-27
  • 2011-06-17
相关资源
最近更新 更多