I'm developing my SwiftUI test app and having some problem with @Published and @ObservedObject.
Here's my Code(FYI I deleted some lines of code and added some dummy values for you to understand easily)
import SwiftUI
struct S0: Identifiable {
var id = UUID()
var arr: [S1] = []
}
struct S1: Identifiable {
var i: Int
var id = UUID()
}
class Model: ObservableObject {
@Published var items: [S0] = [S0(arr: [S1(i: 100)])]
}
struct ContentView: View {
@ObservedObject var testModel = Model()
@State var flag = false
var body: some View {
VStack {
List {
ForEach (self.testModel.items){ item in
Text("\(item.arr.last?.i.description ?? "nil")")
}
}
Button(action: {
self.flag.toggle()
}) {
Text("Add")
}.sheet(isPresented: $flag) {
ModalView(flag: self.$flag).environmentObject(self.testModel)
}
}
}
}
struct ModalView: View {
@Binding var flag: Bool
@EnvironmentObject var testModel: Model
var body: some View {
Button(action: {
if let lastItem = self.testModel.items.last {
var newItem = lastItem
newItem.arr[0].i += 100
self.testModel.items.append(newItem)
}
self.flag.toggle()
}) {
Text("add")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The problem is that when I plus add button, different numbers(+100 to previous number) should be displayed but it is displaying same numbers(100)
As you can see from my code, @Published used struct array which also contains struct array as a child. If I don't have struct array as child, it works fine.
Can anyone please suggest me good solution for this?
Thanks.

self.scoreViewModel.objectWillChange.send()before your changes in your modal view