Skip to content

Latest commit

 

History

History
31 lines (22 loc) · 1011 Bytes

README.md

File metadata and controls

31 lines (22 loc) · 1011 Bytes

StateObject initialisation example

This SwiftUI application demonstrates how to initialise an ObservableObject as a StateObject in a View's init method.

Let's say you have an ObservableObject named ContentViewModel and you have declared it as a StateObject in your View, as follows:

struct ContentView: View {
    @StateObject var viewModel: ContentViewModel
}

Naturally, you will try and initialise viewModel in ContentView's init method as follows:

init(someParam: SomeType) {
    viewModel = ContentViewModel(someParam: someParam)
}

When you try this, you'll get the following compilation error:

Cannot assign to property: 'viewModel' is a get-only property

Fortunately, there's a workaround. See the ContentView.swift file in this project for the workaround.