๐Ÿ”ธstate object

โ•ฑ๐Ÿšง under construction

SwiftUI โŸฉ view โŸฉ state โŸฉ object

A state object is an observable object that is declared and initialized as a property in a view, the view is called an observer of the observable object.

Use @StateObject to declare and initialize a state object in a view.

struct ContentView: View {
    
    // โญ๏ธ declare & initialize a state object (an observable object)
    @StateObject var data = DataModel()

    // UI
    var body: some View { ... }
    
}
// case 1: use the data model in a single view
// ---------------------------------------------
struct ContentView: View {
    
    // โญ๏ธ state object (an observable object)
    @StateObject var data = CreatureZoo()

    // UI
    var body: some View {
        List {
            ForEach(data.creatures) { creature in 
                Text(creature.name)
            }
        }
    }
    
}

Last updated