【问题标题】:Group array of Swift dates by month按月分组 Swift 日期数组
【发布时间】:2018-08-30 13:06:10
【问题描述】:

我有一个 Swift 日期数组:

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

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

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

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

如何按月对日期数组进行分组,无论是函数式还是命令式?

【问题讨论】:

  • 我不知道初始化与分组马特谢谢。方便了解
  • 关键问题是如何表示月份分组
  • @netshark1000,使用这个 :- Dictionary(grouping: dateArray) {$0.month},希望对您有所帮助。

标签: swift nsdate nscalendar


【解决方案1】:

斯威夫特 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]]

【讨论】:

  • 谢谢!我的问题有点复杂。日期对象(来自)是 AppointmentObject 的一部分。我需要按月分组的 AppointmentObjects。 let filterAppointmentsByMonth = { 约会中的约会.filter { $0.from.month == 约会.from.month } } 给出错误(不明确的参考)
猜你喜欢
  • 1970-01-01
  • 2013-04-05
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
相关资源
最近更新 更多