@StateObject

โ•ฑ๐Ÿšง under construction

SwiftUI โŸฉ view โŸฉ state โŸฉ object โŸฉ @StateObject

Use @StateObject to declare and initialize a state object in a view that observes the object's data.

// โญ๏ธ 1. declare a type that conforms to `ObservableObject`
class Zoo : ObservableObject {

    // โญ๏ธ 2. declare published value(s) in this type
    @Published var creatures = [
        Creature(name: "Gorilla", emoji: "๐Ÿฆ"),
        Creature(name: "Peacock", emoji: "๐Ÿฆš"),
    ]
    
}

// content view
struct ContentView: View {

    // โญ๏ธ 3. declare & initialize a state object
    @StateObject var data = Zoo()
    
    var body: some View {
        // 4. access the state object's data in subviews
    }
}

๐Ÿ“— ๅƒ่€ƒ๏ผšSwift Playgrounds (Keep Going with Apps) - Sharing Data Between Views.

๐Ÿ“ CreatureZoo

// โญ๏ธ 1. declare an observable object type
class CreatureZoo : ObservableObject {
    // โญ๏ธ 2. declare published properties
    @Published var creatures = [
        Creature(name: "Gorilla", emoji: "๐Ÿฆ"),
        Creature(name: "Peacock", emoji: "๐Ÿฆš"),
    ]
}

๐Ÿ“ MyApp

@main
struct MyApp: App {
    
    // โญ๏ธ 3. intialize an observable object
    @StateObject var data = CreatureZoo()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                // โญ๏ธ 4. put data in environment
                .environmentObject(data)
        }
    }
}

๐Ÿ“ ContentView

struct ContentView: View {
    
    // โญ๏ธ 5. inject data from environment
    @EnvironmentObject var data : CreatureZoo

    var body: some View {
        // โญ๏ธ 6. access data in subviews
    }
}

Last updated