@StateObject is read-only, so we can't inject it.
The next block of code shows how we could inject 2 presenters through the init, which are then assigned to a @StateObject variable and a @ObservedObject variable.
Notice:
(Feedback issue number: FB7774103)
The next block of code shows how we could inject 2 presenters through the init, which are then assigned to a @StateObject variable and a @ObservedObject variable.
Notice:
Assigning a value directly to a @StateObject works fine. (presenterStateWorking).
Injecting a presenter that is then assigned to a @StateObject doesn't work. Throws an error in the init. (presenterStateNotWorking).
Injecting a presenter that is then assigned to a @ObservedObject works fine. (presenterObserved).
Code Block swift /* (You can drop this chunk of code in a playground) */ import SwiftUI import PlaygroundSupport class Presenter: ObservableObject { @Published var viewModel = ViewModel(number: 42) } struct ViewModel: Equatable { let number: Int } struct ContentView: View { @StateObject var presenterStateWorking = Presenter() @StateObject var presenterStateNotWorking: Presenter @ObservedObject var presenterObserved: Presenter init(presenter1: Presenter, presenter2: Presenter) { self.presenterStateNotWorking = presenter1 /* (error thrown on this line) */ self.presenterObserved = presenter2 } var body: some View { VStack { Text("Hi 🍎 Engineer 😊") .padding() } } } let view = ContentView(presenter1: Presenter(), presenter2: Presenter()) PlaygroundPage.current.liveView = UIHostingController(rootView: view)
(Feedback issue number: FB7774103)
A @StateObject is only meant for instantiating an object at some point in your view hierarchy, as you've done with presenterStateWorking. This attribute tells SwiftUI to create the object only once, regardless of how many times it recreates the enclosing view. It isn't meant for passing an object through the interface, as you've done with presenterStateWorking. For that, use @ObservedObject, as you have with presenterObserved.
For more information about creating and passing around model objects, please see Managing Model Data in Your App.
For more information about creating and passing around model objects, please see Managing Model Data in Your App.