Home > OS >  .onDelete causes a crash because out of index
.onDelete causes a crash because out of index

Time:10-12

Does anyone know why this code cause a fatal error: Index out of range, when I try to delete an item from the list? At the moment I am able to create more textfields and populate them but unable to delete anything without the app crashing.

import SwiftUI

struct options: View {

@State var multiOptions = [""]

var body: some View {
    
    VStack {
        List {
            ForEach(multiOptions.indices, id: \.self) { index in
                TextField("Enter your option...", text: $multiOptions[index])
            }
            .onDelete(perform: removeRow)
        }
        
        Button {
            multiOptions.append("")
        } label: {
            Image(systemName: "plus.circle")
        }

    }

}
func removeRow(at offsets: IndexSet) {
    multiOptions.remove(atOffsets: offsets)
}

}

CodePudding user response:

This seems hard to believe, but apparently the naming of an attribute in the entity as "id" is the cause of this behavior. I changed the name of the UUID attribute to "myID" and the deletions now work. The list view still does not work at all in the preview, but it does now work in the simulator and with a device.

CodePudding user response:

Here is the answer with custom Binding:

struct ContentView: View {
    
    @State var multiOptions = [""]
    
    var body: some View {
        
        VStack {
            List {
                ForEach(multiOptions.indices, id: \.self) { index in

                    TextField("Enter your option...", text: Binding(get: { return multiOptions[index] },
                                                                    set: { newValue in multiOptions[index] = newValue }))
  
                }
                .onDelete(perform: removeRow)
            }
            
            Button {
                multiOptions.append("")
            } label: {
                Image(systemName: "plus.circle")
            }
            
        }
        
    }
    func removeRow(at offsets: IndexSet) {
        multiOptions.remove(atOffsets: offsets)
    }
    
}
  • Related