Because my actual code is a bit more complicated, here is a simplified class structure with which I can reproduce the same unexpected behavior.
This is my base data object which I subclass:
class People: Identifiable {
var name: String
required init(name: String) {
self.name = name
}
}
class Men: People {
}
And then I use another class which acts also as superclass, but also uses a generic type of People
.
class SuperMankind<PlayerType: People> {
var people: [PlayerType] = []
}
class Mankind: SuperMankind<Men> {
}
Now I want to use this this Mankind
subclass in my ViewModel, which is an ObservableObject.
class ViewModel: ObservableObject {
@Published var mankind: Mankind
init(_ m: Mankind) {
mankind = m
}
}
struct TestView: View {
@StateObject var viewModel = ViewModel(Mankind())
var body: some View {
VStack {
Button("Add") {
viewModel.mankind.people.append(Men(name: Int.random(in: 0...1000).description))
}
List {
ForEach(viewModel.mankind.people) {
Text($0.name)
}
}
}
}
}
But my view does not update if I click the add button and I don't know why. I figured out that if I add the following code to my button action the view updates. But this manual call should not be necessary in my opinion so I assume I do something wrong.
viewModel.objectWillChange.send()