Code: Select all
@Query(sort: [SortDescriptor(\BoughtItem.boughtDate, order: .reverse)])
private var allItems: [BoughtItem]
Code: Select all
var sections: [HistorySection] {
toSections(items: allItems)
}
Swift/ContiguousArrayBuffer.swift:675: Schwerwiegender Fehler: Index außerhalb des gültigen Bereichs
im nachfolgenden UI-Update, wenn auf den Abschnitt mit seinem Index zugegriffen wird:
Code: Select all
Text(sections[sectionIndex].date.description)
Code: Select all
struct HistoryView: View {
@Environment(\.modelContext) private var modelContext
@Query(sort: [SortDescriptor(\BoughtItem.boughtDate, order: .reverse)])
private var allItems: [BoughtItem]
var sections: [HistorySection] {
toSections(items: allItems)
}
var body: some View {
NavigationStack {
List {
ForEach(sections.indices, id: \.self) { sectionIndex in
Section(header: HStack {
Text(sections[sectionIndex].date.description)
Spacer()
}) {
ForEach(sections[sectionIndex].boughtItems) { boughtItem in
HStack {
Text(boughtItem.name ?? "")
Spacer()
VStack {
Text(boughtItem.quantity.description)
Text(boughtItem.price.description)
}
}
}
.onDelete { indexSet in
deleteItem(in: sectionIndex, at: indexSet)
}
}
}
}
}
}
private func deleteItem(in sectionIndex: Int, at offsets: IndexSet) {
withAnimation {
let section = sections[sectionIndex]
print("will delete: " + sectionIndex.description + ", offsets: " + offsets.description)
for index in offsets {
let boughtItem = section.boughtItems[index]
modelContext.delete(boughtItem)
}
do {
try modelContext.save()
} catch {
print("error saving: \(error)")
}
}
}
}