I have an app that
- Individually extracts every element of an array (through indices)
- Then bind it to a struct that can make use of that single element (viewing and editing)
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
//Text View
TextView(text: self.$TextArray[index])
.padding()
}
//Array modifying button
Button(action: {
self.TextArray = ["A","B"]
}){
Text(" Shrink array ")
.padding()
}
}
}
}
struct TextView:View {
@Binding var text:String
var body:some View {
Text(text)
}
}
#if DEBUG
struct test_Previews: PreviewProvider {
static var previews: some View {
test()
}
}
#endif
Is there any better way to satisfy the two requirements above without causing this problem or any way to circumvent this problem ? Any responses are really appreciated.