@Published

SwiftUI โŸฉ view โŸฉ state โŸฉ observable object โŸฉ @Published

Use @Published to declare a published value in an observable object type.

// โญ๏ธ 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
    }
}

The @Published attribute is class constrained. Use it with properties of classes, not with non-class types like structures.

Last updated