I have problems with deleting cells that contain a Toggle.
My model looks like this:
class Model: ObservableObject {
@Published var items: [Item]
A possible solution is to use a default value instead of force-unwrapping. When you delete a row in the list, its ItemCell
view may still exist in memory. By using a default value you can prevent crashing (there's no risk of manipulating the wrong item as you can't access this view anymore).
var itemIndex: Int { model.items.firstIndex(where: { $0.id == item.id }) ?? 0 }
Alternatively, you can use an optional index:
struct ItemCell: View {
@EnvironmentObject var model: Model
var item: Item
var itemIndex: Int? { model.items.firstIndex(where: { $0.id == item.id }) }
var body: some View {
Group {
if itemIndex != nil {
Toggle(isOn: $model.items[itemIndex!].isImportant) {
Text(item.text)
}
}
}
}
}