Swift:将日期数组按月数组分组

net*_*000 -6 swift

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

想要的:日期在[[date1,date2],[date3],...]内的月份数组,其中一个月的所有天都应在同一月份的数组内。

有办法做到这一点吗?我认为命令式的方法将很复杂。

Ale*_*lex 5

斯威夫特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)) }
Run Code Online (Sandbox Code Playgroud)

经过测试并在Xcode 9.2游乐场中工作。

输出量

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

假设约会对象的用法

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)) }
Run Code Online (Sandbox Code Playgroud)

另类

这不是您问题的直接答案,但也可能是您问题的可行解决方案。正确地,许多人指出了Dictionary阶级的存在。使用上述Date扩展名,您还可以执行以下操作:

Dictionary(grouping: rawDates) {$0.month}
Run Code Online (Sandbox Code Playgroud)

输出量

您的密钥现在是月份指示器(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]]