Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

ios - How to group array of dates by months in swift?

I am working on a scheduling app. I want all the dates of the given months I am not able to group dates by months that is what I tried but I want a different expected result

extension Date {
    static func dates(from fromDate: Date, to toDate: Date) -> [Date] {
        var dates: [Date] = []
        var date = fromDate

        while date <= toDate {
            dates.append(date)
            guard let newDate = Calendar.current.date(byAdding: .day, value: 1, to: date) else { break }
            date = newDate
        }
        return dates
    }
    var month: Int {
        return Calendar.current.component(.month, from: self)
    }
}

let fromDate = Calendar.current.date(byAdding: .day, value: 30, to: Date())
let datesBetweenArray = Date.dates(from: Date(), to: fromDate!)
var sortedDatesByMonth: [[Date]] = []
let filterDatesByMonth = { month in datesBetweenArray.filter { $0.month == month } }
(1...12).forEach { sortedDatesByMonth.append(filterDatesByMonth($0)) }

The result is in this format [[], [], [], [], [], [], [2019-07-31 03:51:19 +0000],……., [], [], [], []]

This kinda result I want expecting

struct ScheduleDates {
    var month: String
    var dates: [Date]

    init(month: String, dates: [Date]) {
        self.month = month
        self.dates = dates
    }
}
var sections = [ScheduleDates]()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to group your dates by month you can create a Dictionary like this:

Dictionary(grouping: datesBetweenArray, by: { $0.month })

This results in the following output of the format [Int: [Date]]

The key of the dictionary will be your month.

Now you can initialize your scheduleDates struct by looping through this dictionary in this way:

var sections = Dictionary(grouping: datesBetweenArray,
                          by: ({$0.month}))
    .map { tuple in
        ScheduleDates(month: String(tuple.0), dates: tuple.1)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...