Просто создайте структуру, которая отслеживает год, месяц и день.
struct DateCluster {
let day: Int
let month: Int
let year: Int
var dates: [Date] = []
init(date: Date) {
let cal = Calendar.current
day = cal.component(.day, from: date)
month = cal.component(.month, from: date)
year = cal.component(.year, from: date)
dates.append(date)
}
func doesDateBelong(_ date: Date) -> Bool {
let cal = Calendar.current
return cal.component(.day, from: date) == day
&& cal.component(.month, from: date) == month
&& cal.component(.year, from: date) == year
}
}
А вот использование:
func makeDate(year: Int, month: Int, day: Int) -> Date? {
let cal = Calendar.current
let components = DateComponents(year: year, month: month, day: day)
return cal.date(from: components)
}
var clusters: [DateCluster] = []
var dates = [
makeDate(year: 2020, month: 4, day: 20),
makeDate(year: 2020, month: 4, day: 19),
makeDate(year: 2020, month: 4, day: 19),
makeDate(year: 2020, month: 4, day: 18),
makeDate(year: 2020, month: 4, day: 18),
].compactMap { $0 }
for date in dates {
if let index = clusters.firstIndex(where: { $0.doesDateBelong(date) }) {
clusters[index].dates.append(date)
} else {
clusters.append(.init(date: date))
}
}
В результате ниже будет массив из массива даты все сгруппированы по году, месяцу и дню.
let groupedDates = clusters.map { $0.dates }