skip to Main Content

When executing the .onDelete function, I am getting an index out of range. I have successfully used onDelete elsewhere in my app, deleting data directly from core data. This version is to only delete from a list not stored in core data.

I created some temporary lists for testing, and using this .onDelete was successful. The successful test cases were with arrays that already had data in them and did not need to be initialized. The array used in the code below is one that is initialized when the user lands on this page – could this be why it is failing?

There is lots of code inside this struct, but the relevant parts are below:

@State var recipeStep: [String]

More code, eventually reaching the ForEach causing the problems

            List {
                ForEach(0..<recipeStep.count, id: .self) { index in
                            HStack {
                                Text(String(stepNumber[index]) + ".").bold()
                                TextField("", text: $recipeStep[index]).multilineTextAlignment(.leading).padding(.leading)
                            }
                }.onDelete { (indexSet) in
                    recipeStep.remove(atOffsets: indexSet)}

Any thoughts as to why I am getting an index out of range error?

2

Answers


  1. Chosen as BEST ANSWER

    I was able to get this to work by modifying my textfield to work the following way:

    EditorView(container: self.$recipeStep, index: index, text: recipeStep[index])
    

    The solution was found here, posted by Asperi: https://stackoverflow.com/a/58911168/12299030

    I had to modify his solution a bit to fit my forEach, but overall it works perfectly!


  2. You loop with recipeStep in

    ForEach(0..<recipeStep.count, id: .self) { index in
    

    While you use both $recipeStep[index] and stepNumber[index]

    So recipeStep and stepNumber should be of same size to avoid crashes or better union them in 1 model

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search