Building Robust ViewModels

Feb 28 2025 · Swift 5.9, iOS 17, Xcode 15.3

Lesson 02: State Management in ViewModels

Demo 1

Episode complete

Play next episode

Next
Transcript

Open TheMet app in the Starter folder or continue with your project from lesson 1.

In Lesson 1, you made TheMetStore conform to Observable:

@Observable class TheMetStore {
  var objects: [Object] = []
  ...
}

TheMetStore publishes objects, an array of Object values.

In ContentView, you instantiated TheMetStore as a @State property:

@State var store = TheMetStore()

and displayed a List of objects:

@State var store = TheMetStore()
...
  List(store.objects) { object in
    ...
  }

This list redraws whenever the objects array changes.

None of the other views need store, so, to see that you don’t need any property wrapper when you pass it to a subview, you’ll create it in the App and pass it to ContentView.

Start by copying the store declaration, then comment it out and add the following line:

var store: TheMetStore

Down in the #Preview, add the store parameter:

ContentView(store: TheMetStore())

Now, in TheMetApp, paste that declaration you copied from ContentView:

@State var store = TheMetStore()

And pass it to ContentView:

ContentView(store: store)

OK, back to ContentView. In a pre-iOS-17 app, you would’ve made store an ObservedObject to tell SwiftUI that it needs to be observed. However, the @Observable protocol takes care of this in the new observation framework.

Tap search and enter a query. The List observes the change in store.objects and redraws itself.

Now, what about the other properties in TheMetStore? Can ContentView observe and react if service or maxIndex changes? Keep going to find out.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Adding Observation Properties Instruction