斯威夫特 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 操场上测试和工作。
输出
[[], [], [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 { $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)) }
替代方案
不是您问题的直接答案,但也可能是您问题的可行解决方案。许多人正确地指出了Dictionary 类的存在。使用上面提到的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]]