Reading time: 1 min
This quick recipe shows how to set a @StateObject in a SwiftUI View's initializer.
Basically, you're trying to do this:
struct MyView: View {
@StateObject private var viewModel: ViewModel
init(someParams: String) {
viewModel = ViewModel(params: someParams)
}
But you keep running into this error:
The solution is to initialize the StateObject
directly and assign it to underlying value of the @StateObject
property wrapper:
init(someParams: String) {
_viewModel = StateObject(wrappedValue: ViewModel(params: someParams))
}