I have an app that
- Has a collection of editable items (like a bunch of notes)
- Need to bind these items to a child view that can edit each item (like a note editor)
But every time the array reduces in size, it causes an index out of range error that is not directly because of my code
As far as I know, it's because: after the loop refreshes with the changed array, the views it created before somehow isn't completely removed and still trying access the out of range part. But that's all I can figure out myself
Here is my sample code:
import SwiftUI
struct Test: View {
@State var textArray = ["A","B","C"]
var body: some View {
VStack {
ForEach(textArray.indices, id: \.self){ index in
TextView(text: self.$textArray[index])
.padding()
}
//Array modifying button
Button(action: {
textArray = ["A","B"]
}) {
Text("Shrink array")
.padding()
}
}
}
}
struct TextView: View {
@Binding var text: String
var body: some View {
Text(text)
}
}
Is there any better way to satisfy the two requirements above without causing this problem? Thank you.