MasterOnce
HomeBlogHow-To
3 min readMar 12, 2026
Swift

How to Use ObservableObject

Share state across multiple views.

Steps

  1. Paste the view into a SwiftUI file.
  2. Set it as a preview or root view.
  3. 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.