简体   繁体   English

快速使用 DateComponents 键对字典进行排序

[英]Sorting dictionary with DateComponents keys in swift

Hi Guys I briefly explain my problem.嗨,伙计们,我简要解释一下我的问题。

From my database I get an array of HistoryItem , a custom type that contains a simple Date property inside it:从我的数据库中,我得到了一个HistoryItem数组,这是一个自定义类型,其中包含一个简单的Date属性:

struct HistoryItem {
     let date: Date
     let status: Status // Not important for my problem
}

I want to group this data by year and month , I thought the best way was a dictionary with key DateComponents :我想按年和月对这些数据进行分组,我认为最好的方法是使用带有键DateComponents的字典:

// ungroupedHistory is already fetched and is of type [HistoryItem]

var groupedHistory: [DateComponents : [HistoryItem]]

groupedHistory = Dictionary(grouping: ungroupedHistory) { (historyItem) -> DateComponents in
     let calendar = Calendar.current
     let components = calendar.dateComponents([.year, .month], from: hisoryItem.date)
     return components
}

The result is as expected but the problem is that it is unsorted, and it is obvious that this is the case since the dictionary by definition is an unsorted collection.结果如预期,但问题是它是未排序的,很明显,这是因为字典根据定义是一个未排序的集合。

How can i get a sorted by date copy of this dictionary?我怎样才能得到这本字典的按日期排序的副本?

I've tried something like this:我试过这样的事情:

let sortedDict = groupedHistory.sorted {
       $0.key.date.compare($1.key.date) == .orderedDescending
}

But I just get an array with keys of type:但我只是得到一个带有类型键的数组:

[Dictionary<DateComponents, [HistoryItem]>.Element]

Thanks in advance!提前致谢!

You need to do this in 2 steps, first get an array with the dictionary keys sorted您需要分 2 步执行此操作,首先获取一个已排序字典键的数组

let sortedKeys = groupedHistory.keys.sorted {
    $0.year! == $1.year! ? $0.month! < $1.month! : $0.year! < $1.year!
}

and then use that array to access the values in your dictionary in a sorted manner然后使用该数组以排序方式访问字典中的值

for key in sortedKeys {
    print(groupedHistory[key])
}

A dictionary is unordered by definition.字典根据定义是无序的。

To get a sorted array you could create a wrapper struct要获得排序数组,您可以创建一个包装结构

struct History {
    let components : DateComponents
    let items : [HistoryItem]
}

then sort the keys and map those to an array of History然后对键进行排序并将它们映射到History数组

let sortedKeys = groupedHistory.keys.sorted{($0.year!, $0.month!) < ($1.year!, $1.month!)}
let history = sortedKeys.map{History(components: $0, items: groupedHistory[$0]!)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM