🔸published value
SwiftUI ⟩ view ⟩ state ⟩ observable object ⟩ published value
In an observable object, a property declared by adding @Published property wrapper that notifies all observers when its value is about to change. When the value changes, SwiftUI updates all views that use its data. Also called a published property.
// ⭐️ 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
}
}
ObservableObject:declare an observable object type.
@Published:declare a published value in an observable object type.
@StateObject:initialize an observable object.
Last updated
Was this helpful?