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))
}
Search our recipes
Related Posts
- 100 Pull to refresh with SwiftUI ScrollView (Updated 08/21)
- 100 SwiftUI Drag To Reorder ForEach / Stack / Grid
- 100 Send mail in SwiftUI
- 100 SwiftUI Text with HTML via NSAttributedString
- 100 Easy data pagination with SwiftPaging
Check out the companion apps!
Our free companion app and XCode Extension brings 100+ SwiftUI recipes right at your fingertips! Get a preview of it in the Online Companion.
Have a recipe for us?
Get in touch and let's grow the cookbook together!