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
I was able to get this to work by modifying my textfield to work the following way:
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!
You loop with
recipeStep
inWhile you use both
$recipeStep[index]
andstepNumber[index]
So
recipeStep
andstepNumber
should be of same size to avoid crashes or better union them in 1 model