3 min readMar 12, 2026
SwiftHow to Use ObservableObject
Share state across multiple views.
Steps
- Paste the view into a SwiftUI file.
- Set it as a preview or root view.
- Update state or bindings to match your data.
Copy and paste
import SwiftUI
final class CounterModel: ObservableObject {
@Published var count = 0
}
struct CounterScreen: View {
@StateObject private var model = CounterModel()
var body: some View {
VStack {
Text("Count: (model.count)")
Button("Add") { model.count += 1 }
}
}
}Notes
- Use @State for local values and bindings for child views.
- Extract subviews when the body grows.
