This question comes up so frequently that it would be extremely appreciated if someone on the SwiftUI team or a DTS representative could chime in on this. The vast majority of sample code and documentation assumes a view model can be created without any parameters to its initializer, which is not always the case. And in the Fruta example app a single Model is used for the entire application, which really isn't realistic for larger scale applications.
I've resorted to the following design pattern but I remain unsure if this is considered a "correct" way to initialize an @StateObject property:
struct ParentView: View {
var body: some View {
ChildView(viewModel: ChildViewModel(someValue: "foo"))
}
}
class ChildViewModel: ObservableObject {
init(someValue: Any) {
}
}
struct ChildView: View {
@StateObject var viewModel: ChildViewModel
}
This pattern appears to work correctly and doesn't require the small "hack" of using the underscore to initialize the @StateObject, which appears to be discouraged based on my reading of the documentation:
StateObject.init(wrappedValue:)
// You don’t call this initializer directly. Instead, declare a property with the
// @StateObject attribute in a View, App, or Scene, and provide an initial value:
struct MyView: View {
@StateObject var model = DataModel()
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: