1

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


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

4

1 回答 1

1

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

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

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

于 2021-07-26T00:38:39.807 回答