SwiftUI: Index out of range when deleting cells with toggle

前端 未结 1 1422
一向
一向 2021-01-21 18:50

I have problems with deleting cells that contain a Toggle.

My model looks like this:

class Model: ObservableObject {
    @Published var items: [Item]
    
         


        
相关标签:
1条回答
  • 2021-01-21 19:32

    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)
                    }
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题