๐Ÿ”ธpublished value

SwiftUI โŸฉ view โŸฉ state โŸฉ observable object โŸฉ published value

// โญ๏ธ 1. declare an observable object type
class CreatureZoo : ObservableObject {

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

// content view
struct ContentView: View {

    // โญ๏ธ 3. initialize an observable object
    @StateObject var data = CreatureZoo()
    
    var body: some View {
        // โญ๏ธ 4. access `data.creatures` in subviews
    }
}

Last updated

Was this helpful?