swift 需要按键排序的字典问题

swift Dictionary problem where it needs to be ordered by the key

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


  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,但它似乎是一个外部包?

正如 jnpdx 所说,字典方法 sorted() returns 类型为 (Key, Value) 的元组数组(因此在您的情况下为 (Date, Int)。)

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

或者,您可以对字典中的键进行排序,然后使用它们为您的内容编制索引。