我想对我定义为的 Dictionary itemDictionary 进行排序:
var itemDictionary = [String: [Items]]()
itemDictionary = itemDictionary.sorted { $0.0 < $1.0 }
但随后我收到以下错误代码:
Cannot assign value of type '[(key: String, value: [Items])]' to type '[String : [Items]]'
有人知道为什么会这样吗?
最佳答案
Dictionary
根据定义是无序的。您只能调用sorted
在上面,因为自 Swift 4 以来,Dictionary
符合 Collection
, 但由于 Dictionary
的无序性质类型,调用的返回值sorted
在 Dictionary
上将是 Array<(key: Key,value: Value)>
,所以一个元组数组,其中元组包含键值对。
如果您需要排序的数据结构,您应该考虑使用实际上可以排序的数据结构。
关于swift - 在 Swift 中排序失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47681609/