Вы должны использовать Dictionary(grouping:by:)
по-другому. Вы должны возвращать значение, по которому хотите группировать, а не для каждого урока отдельную группу.
Помощники
struct Lesson {
let lessonDate: Date
}
extension Date {
func addDays(_ days: Int) -> Date {
return Calendar.current.date(byAdding: .day, value: days, to: self)!
}
func addMonths(_ months: Int) -> Date {
return Calendar.current.date(byAdding: .month, value: months, to: self)!
}
var month: Date {
let calendar = Calendar.current
return calendar.date(from: calendar.dateComponents([.month, .year], from: self))!
}
var prettyMonth: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
formatter.locale = Calendar.current.locale!
return formatter.string(from: self)
}
var prettyDate: String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
formatter.locale = Calendar.current.locale!
return formatter.string(from: self)
}
}
Пример
func testing() {
let lessons: [Lesson] = [
.init(lessonDate: Date().addDays(2)),
.init(lessonDate: Date().addDays(3)),
.init(lessonDate: Date().addMonths(1).addDays(1)),
.init(lessonDate: Date().addMonths(1).addDays(2)),
.init(lessonDate: Date().addMonths(1).addDays(3)),
.init(lessonDate: Date().addMonths(3)),
]
let groupedDict = Dictionary(grouping: lessons, by: { $0.lessonDate.month })
groupedDict
.sorted(by: { a, b in a.key < b.key })
.forEach {
print("----- \($0.key.prettyMonth) -----")
$0.value.forEach {
print("\($0.lessonDate.prettyDate)")
}
}
}
Производит
----- August 2018 -----
29. Aug 2018 at 19:38:13
30. Aug 2018 at 19:38:13
----- September 2018 -----
28. Sep 2018 at 19:38:13
29. Sep 2018 at 19:38:13
30. Sep 2018 at 19:38:13
----- November 2018 -----
27. Nov 2018 at 19:38:13