I want to display a SwiftData Model in my List and have it grouped by month. So each section will list the items with their date falling in that month. An example would be like below:
@Model
final class Item {
var name: String?
var date: Date?
init(name: String? = nil, date: Date? = nil) {
self.name = name
self.date = date
}
}
struct ContentView: View {
@Query var items: [Item]
var body: some View {
let groupedDuties = Dictionary(grouping: items) { (element) -> String in
return element.date!.dateString()
}
List {
ForEach(groupedDuties.sorted(by: { $0.key > $1.key }), id: \.key) { group in
Section(header: Text(group)) {
ForEach(group.value, id: \.id) { item in
Text(item.name ?? "")
}
}
}
}
}
}
This works well for a relatively small number of items. But with several thousand items the list slows down significantly when initially loading and becomes unusable. Is there another way to sort the data into groups without the performance hit?




