按月对 Swift 个日期的数组进行分组

Group array of Swift dates by month

我有一组 Swift 个日期:

[date1, date2, date3, ..., dateN]

我想按月对这些日期进行分组:

[
    [date1, date2],
    [date3],
    ...
    [dateN],
]

一个月中的所有日期都应该在同一个月份数组中。

如何按功能或命令按月对日期数组进行分组?

Swift 4

我会这样做:

extension Date {
    
    var month: Int {
        return Calendar.current.component(.month, from: self)
    }
    
}

// some random arbitrary dates
let rawDates = [Date(), Date().addingTimeInterval(100000.0), Date().addingTimeInterval(100000000.0)]
// the desired format
var sortedDatesByMonth: [[Date]] = []

// a filter to filter months by a given integer, you could also pull rawDates out of the equation here, to make it pure functional
let filterDatesByMonth = { month in rawDates.filter { [=10=].month == month } }
// loop through the months in a calendar and for every month filter the dates and append them to the array
(1...12).forEach { sortedDatesByMonth.append(filterDatesByMonth([=10=])) }

Xcode 9.2 操场上测试和工作。

输出

[[], [], [2018-03-21 12:29:10 +0000, 2018-03-22 16:15:50 +0000], [], [2021-05-21 22:15:50 +0000], [], [], [], [], [], [], []]

假设的 AppointmentObject 的用法

extension Date {
    
    var month: Int {
        return Calendar.current.component(.month, from: self)
    }
    
}

// some random arbitrary dates
let appointments = [AppointmentObject(), AppointmentObject(), AppointmentObject()]
// the desired format
var sortedAppointmentsByFromMonth: [[AppointmentObject]] = []

// a filter to filter months by a given integer, you could also pull rawDates out of the equation here, to make it pure functional
let filterFromDatesByMonth = { month in appointments.filter { [=11=].from.month == month } }
// loop through the months in a calendar and for every month filter the dates and append them to the array
(1...12).forEach { sortedAppointmentsByFromMonth.append(filterFromDatesByMonth([=11=])) }

备选

不是您问题的直接答案,但也许也是您问题的可行解决方案。很多人理直气壮地指出了Dictionaryclass的存在。使用上面提到的 Date 扩展,你也可以这样做:

Dictionary(grouping: rawDates) {[=12=].month}

输出

您的密钥现在是月份指标(5 是 5 月,3 是 3 月)

[5: [2021-05-21 22:46:44 +0000], 3: [2018-03-21 13:00:04 +0000, 2018-03-22 16:46:44 +0000]]