I’ve a MainViewModel that holds an array of enums with related objects. Nevertheless, once I use this in a SwiftUI view, the variable loses its @Printed wrapper, and the UI does not replace or get notified of adjustments. How can I protect the @Printed standing of the variable?
This is my code appear like:
// Enum with related varieties
enum ViewType: Hashable, Identifiable {
case .a(ViewModelA)
case .b(ViewModelB)
case .c(ViewModelC)
}
// lessons utilized in related varieties
class ViewModelA: ObservableObject {
@Printed var listIndex: Int = 1
//another properties
}
class ViewModelB: ObservableObject {
@Printed var title: String = "good day"
//another properties
}
class ViewModelC: ObservableObject {
@Printed var isOn: Bool = false
//another properties
}
// then I create an array in my mainViewModel
// to make use of in my SwiftUI view
class MainViewModel: ObservableObject {
@Printed var viewTypeArray: [ViewType] = [] // add gadgets to it primarily based on the backend response (assume I've 4 gadgets)
}
// then I take advantage of the viewModel in my opinion
struct MyView: View {
@ObservedObject viewModel: MainViewModel
init(viewModel: MainViewModel) {
self.viewModel = viewModel
}
var physique: some View {
ForEach(viewModel.viewTypeArray) { view in
case .a(let viewModelA):
// I show one thing
// I unfastened the ObservableObject wrapper
// then I lose the connection to @Printed wrapper properties ex: `listIndex`
// and no ui updates will set off right here
case .b(let viewModelB):
// I show one thing
// I unfastened the ObservableObject wrapper
// then I lose the connection to @Printed properties ex: `title`
// and no ui updates will set off right here
case .c(let viewModelC):
// I show one thing
// I unfastened the ObservableObject wrapper
// then I lose the connection to @Printed properties ex: `isOn`
// and no ui updates will set off right here
}
}
}
I attempted utilizing an ObservableObject wrapper for every youngster ViewModel (e.g., ViewModelA, ViewModelB) to keep up a direct reference to the view, however this did not work. I wish to use an enum with related varieties, together with @ObservableObject and @Printed wrappers, to make sure that adjustments correctly replace the SwiftUI view.