【发布时间】: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,其中包含一个代表keys和values的元组:developer.apple.com/documentation/swift/dictionary/…