Skip to content

Latest commit

 

History

History

App7

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

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.