Building Robust ViewModels

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

Lesson 03: Data Binding Techniques

Demo 1

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Open TheMet app in the Starter folder. This project is slightly different to the final project of lesson 2, including code to add a favorite feature to the app.

@State var store = TheMetStore()
var body: some Scene {
  WindowGroup {
    ContentView(store: store)
  }
}
var store: TheMetStore

Subview of ObjectView Needs to Access Store

The List in ContentView passes an object to ObjectView or a URL to SafariView — neither view needs access to store.

Text("store.objects.count objects in store")

@Environment

First, in TheMetApp, replace ContentView(store: store) with:

ContentView()
  .environment(store)
@Environment(TheMetStore.self) var store
ContentView()
  .environment(TheMetStore())
Text("\(store.objects.count) objects in store")
#Preview {
  CountView()
    .environment(TheMetStore())
}
#Preview {
  ...
  return ObjectView(object: object)
    .environment(TheMetStore())
}
See forum comments
Cinema mode Download course materials from Github
Previous: View Models & Environment Property Instruction Next: Instruction