🔸state object

╱🚧 under construction

SwiftUIviewstate ⟩ 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

Was this helpful?