Build an app with SwiftData

Check out “Meet SwiftData” to cover the basics.  This is a code along session (https://developer.apple.com/wwdc23/10154) and you should download the code from https://developer.apple.com/documentation/SwiftUI/Building-a-document-based-app-using-SwiftData 

The code along get’s you to build a cross platform code flashcard app.  

Meet the App

  • This is the flash card app located at the above links.

SwiftData models

  • If you are converting to SwiftData you will change your class to @Model and remove ObservableObject and @Published from it.  Then in the Views were you update the object change from @ObservedObject to @Bindable
  • For more on this. Check out “Discover Observation with SwiftUI” session  – Discover Observation in SwiftUI 

Querying models to display in UI

  • Changing your content view from @State to @Query and removing the sample data assignment allows you to now directly get your data from SwiftData
  • @Query is a property wrapper that gets data from Swift Data and triggers view updates,  You can add simple syntax for (sort: \.ValueoSortOn) (order: ) and (filter:), and you can have multiple @Query properties in a view.
  • .modelContainer(for: NameOfClass.self) this will setup a model container, which creates the whole storage stack.  Every view can have a single model container.  If you don’t have set one up, it won’t save or query.  Just set it up in the WindowGroup scene.
  • You should update your Previews with sample data.  Creating an in memory set of sample data achieves this.  Look at how this is done in the “PreviewSampleData.swift” file in the project (This failed for me and persisted on both the starter project code along, and the completed final project provided above, I am guessing this may be a Xcode bug).

Creating and updating

  • You need to accept the modelContext of the view in order to do saves and updates.  Just grab it from the Environment
  • Save is automatic for you

[Bonus] Document-based apps

  • Changing to document based app, you can turn the flash card deck as separate instances. To do this, you will have to define the package type but it is almost trivial doing this.