Hi,
I recently started experiencing the following bug in the code listed below. The app is a dieting/calorie logging app with a function that presents a List() of calories in different days, separated into sections for each Meal as derived from an array of Meals. Part of this functionality is that the user can swipe an entry in the List to delete one.
If the user has one entry and they delete it, behaviour is as expected.
If they have more than one entry and they delete one, behaviour is as expected.
If they have more than one entry and they delete two items, one after another, the app crashes with the message "Invalid number of items in section 0".
If they have more than one entry and they delete one, then go back to the main screen of the app, then delete another one, behaviour is as expected.
Searches online suggest that this is because the array underpinning the list has not updated. However the app crashes before it has even reached the delete() function called by onDelete, so there is no opportunity to update the model before something refreshes and the app crashes.
Does anyone have any idea how to resolve this? This code worked fine up until iOS 18.
List {
if list.budgieData.count != 0 {
ForEach(list.mealList.indices, id: \.self) { idx in
Section(header: Text(list.mealList[idx].name)) {
ForEach(list.budgieData.indices, id: \.self) { entryIdx in
if list.budgieData[entryIdx].meal == list.mealList[idx].mealUUID {
CalorieEntryView(calories: list.budgieData[entryIdx].calories, narrative: list.budgieData[entryIdx].narrative ?? "Quick calories", realEntry: list.budgieData[entryIdx].realEntry, date: list.budgieData[entryIdx].date)
}
}.onDelete(perform: delete)
}
}
} else {
Text("You have no calories logged in Budgie Diet on this day.")
}
if list.hkCalories != 0 {
Section(header: Text("Calories from other apps"), footer: Text("These are calories logged in Health by other apps. You'll need to go to the app that logged them to change or delete them.")) {
CalorieEntryView(calories: list.hkCalories, narrative: "Calories from other apps", realEntry: false, date: list.curDate)
.deleteDisabled(true)
}
}
}.listStyle(.grouped)