I would like to know if there is currently (at the time of asking, the first Xcode 12.0 Beta) a way to initialize a @StateObject with a parameter coming from an
I guess I found a workaround for being able to control the instantiation of a view model wrapped with @StateObject. If you don't make the view model private on the view you can use the synthesized memberwise init, and there you'll be able to control the instantiation of it without problem. In case you need a public way to instantiate your view, you can create a factory method that receives your view model dependencies and uses the internal synthesized init.
import SwiftUI
class MyViewModel: ObservableObject {
@Published var message: String
init(message: String) {
self.message = message
}
}
struct MyView: View {
@StateObject var viewModel: MyViewModel
var body: some View {
Text(viewModel.message)
}
}
public func myViewFactory(message: String) -> some View {
MyView(viewModel: .init(message: message))
}