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:

Screenshot%202021-09-12%20at%2009.53.06

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))
}

Next Post Previous Post