I'm quite new to IOS development so please bear with me if I have used the code in a completely improper way.
I use swiftui 2 and my problem is that I have in my data structure an array which contains information I would like to present in another view via ForEach. That's so far working but if I change the array within one of the subviews, then I get an index out of range error.
Here's the example data structure:
struct Test {
var id: String
var array : Array<String>
}
The EnvironmentObject:
class DBhandler: ObservableObject {
@Published var arrays: Test
init(arrays: Test) {
self.arrays = arrays
}
}
The app file:
@main
struct DummyApp: App {
@ObservedObject var dbhandler = DBhandler(arrays: Test(id: "1", array: ["Car", "Bus", "Train"]))
var body: some Scene {
WindowGroup {
ContentView().environmentObject(dbhandler)
}
}
}
The MainView:
struct ContentView: View {
@EnvironmentObject var dbhandler: DBhandler
var body: some View {
VStack{
ForEach(dbhandler.arrays.array.indices, id: \.self) {index in
SubView(index: index)
}
}
}
}
And the SubView:
struct SubView : View {
@EnvironmentObject var dbhandler: DBhandler
let index: Int
var body: some View {
VStack{
Text(dbhandler.arrays.array[index]) <--- here's the index out of range error
Button(action: {
dbhandler.arrays.array.remove(at: index)
}, label: {
Text("Remove object")
})
}
}
}
My assumption is that the ForEach does not refers to the latest dbhandler.arrays.array.indices but rather to an old stored one but I don't know how to circumvent it.
Does anyone of you has an idea on how I could fix this?
Any help is much appreciated :)