繁体   English   中英

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

[英]Sorting dictionary with DateComponents keys in swift

嗨,伙计们,我简要解释一下我的问题。

从我的数据库中,我得到了一个HistoryItem数组,这是一个自定义类型,其中包含一个简单的Date属性:

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

我想按年和月对这些数据进行分组,我认为最好的方法是使用带有键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
}

结果如预期,但问题是它是未排序的,很明显,这是因为字典根据定义是一个未排序的集合。

我怎样才能得到这本字典的按日期排序的副本?

我试过这样的事情:

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

但我只是得到一个带有类型键的数组:

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

提前致谢!

您需要分 2 步执行此操作,首先获取一个已排序字典键的数组

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

然后使用该数组以排序方式访问字典中的值

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

字典根据定义是无序的。

要获得排序数组,您可以创建一个包装结构

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

然后对键进行排序并将它们映射到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