Observable Objects
Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 40 of 50.
Data that several views share, or that has its own logic, goes in a class. It conforms to ObservableObject, and each property the screen displays is marked @Published:
class Cart: ObservableObject {
@Published var count = 0
func add() {
count += 1
}
}The view that creates the object stores it with @StateObject. SwiftUI keeps that one object alive while the view is on screen, and redraws the view whenever a published property changes:
struct ContentView: View {
@StateObject private var cart = Cart()
var body: some View {
VStack {
Text("Items: \(cart.count)")
Button("Add to cart") {
cart.add()
}
}
}
}A child view that receives an existing object from its parent marks it @ObservedObject instead: it watches the object but does not own it.
Challenge
MediumThe Scoreboard class is not connected to the screen. Make it an ObservableObject with a @Published points, store it in ContentView with @StateObject, and make the button call scoreboard.score(). The text must read Points: 10 after one tap.
Try it yourself
import SwiftUI
@main
struct CoddyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction to SwiftUI
Practice on your own: Swift playground