Swift:将日期数组分组为月份数组

Swift:将日期数组分组为月份数组,swift,Swift,给定的:日期数组:[date1,date2,date3,…,dateN] 通缉犯:包含日期的月份数组:[[date1,date2],[date3],…] 其中,一个月的所有日期都应位于同一个月数组中 有没有办法做到这一点?我想命令式的方式会很复杂。Swift 4 我当然会这样做,我希望这会有所帮助: extension Date { var month: Int { return Calendar.current.component(.month, from: self

给定的:日期数组:[date1,date2,date3,…,dateN]

通缉犯:包含日期的月份数组:[[date1,date2],[date3],…] 其中,一个月的所有日期都应位于同一个月数组中


有没有办法做到这一点?我想命令式的方式会很复杂。

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 { $0.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($0)) }
Xcode 9.2操场上测试和工作

输出

假设任命对象的用法

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 { $0.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($0)) }
备选方案

这不是对你问题的直接回答,但也可能是解决你问题的可行办法。许多人理直气壮地指出了
字典
类的存在。使用上述
Date
扩展名,您还可以执行以下操作:

Dictionary(grouping: rawDates) {$0.month}
输出

您的关键点现在是月份指标(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]

是的,有几种方法可以做到这一点。到目前为止你试过了吗?没有-任何帮助都是值得的。我不知道init,谢谢。关键问题是如何表达月份分组谢谢!我的问题有点复杂。日期对象(从)是AppointmentObject的一部分。我需要按月份分组的AppointmentObjects。让FilterAppointsByMonth={appointment in appointment.filter{$0.from.month==appointment.from.month}给出一个错误(不明确的引用)谢谢!你的解决方案对我帮助很大!