@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.
- @StateObject:initialize an observable object. 
Last updated
Was this helpful?