Swift Academy · Lesson

@ObservableObject and @StateObject

Creating reference-type models that drive SwiftUI views via @Published.

Lesson 2 of 412 steps

@ObservableObject and @StateObject is a free Swift Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

Welcome

For complex state shared across multiple views, use reference-type models conforming to `ObservableObject`, owned by `@StateObject` or observed by `@ObservedObject`.

Defining an ObservableObject

```swift class CartModel: ObservableObject { @Published var items: [CartItem] = [] @Published var total: Double = 0 func add(_ item: CartItem) { items.append(item) } } ```

@StateObject — Ownership

```swift struct ShopView: View { @StateObject private var cart = CartModel() // owns the model var body: some View { CartList(cart: cart) } } ``` Use `@StateObject` when the view creates and owns the model.

@ObservedObject — External Ownership

```swift struct CartList: View { @ObservedObject var cart: CartModel // doesn't own; passed in var body: some View { List(cart.items) { item in Text(item.name) } } } ```

The Difference

• `@StateObject` — view creates model; model persists across re-renders • `@ObservedObject` — model is passed in; can be recreated by parent Using `@ObservedObject` where `@StateObject` is needed causes the model to reset unexpectedly.

objectWillChange Subscription

SwiftUI automatically subscribes to `objectWillChange` when using `@StateObject` or `@ObservedObject`. Every `@Published` change triggers a re-render.

Manual objectWillChange

```swift class Timer: ObservableObject { var count = 0 func tick() { objectWillChange.send() // manual notification count += 1 } } ```

Nested ObservableObjects

SwiftUI doesn't observe nested ObservableObjects automatically. Forward changes manually: ```swift class Parent: ObservableObject { @Published var child = ChildModel() private var cancel: AnyCancellable? init() { cancel = child.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() } } } ```

@Observable Macro (Swift 5.9)

```swift @Observable class Counter { var count = 0 } // No ObservableObject, no @Published, no @StateObject needed // SwiftUI automatically tracks access ```

Testing ObservableObject

```swift func testCart() { let cart = CartModel() cart.add(CartItem(name:"Apple",price:1.0)) XCTAssertEqual(cart.items.count, 1) XCTAssertEqual(cart.total, 1.0) } ```

Quick Check

When should you use `@StateObject` vs `@ObservedObject`?

Recap

Key takeaways: • `ObservableObject` + `@Published` = reactive model • `@StateObject` — view owns model; persists across re-renders • `@ObservedObject` — model passed in; external ownership • `objectWillChange.send()` for manual notifications • Swift 5.9 `@Observable` macro replaces most of this Next: @EnvironmentObject.
Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “@ObservableObject and @StateObject” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “@ObservableObject and @StateObject”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “@ObservableObject and @StateObject”?

Creating reference-type models that drive SwiftUI views via @Published. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “@ObservableObject and @StateObject” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. @Binding: Two-Way Data Flow
  2. @ObservableObject and @StateObject
  3. @EnvironmentObject for Shared State
  4. Single Source of Truth and Unidirectional Flow
← Back to Swift Academy