@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?