Lesson 05 · iOS with Swift & SwiftUI
iOS: Persistence with SwiftData & UserDefaults
Making data survive relaunches: the persistence ladder from in-memory state through UserDefaults and files to SwiftData, UserDefaults mechanics and their limits, the @Model macro for persistent classes, ModelContainer and ModelContext, live-updating @Query views with #Predicate filtering, a full CRUD walkthrough, schema versioning when shipped models change, and a decision table for choosing storage.
Prerequisites: iOS: State, Data Flow & Lifecycle
Learning objectives
By the end of this lesson, you will be able to:
- Place a given piece of data on the persistence ladder - in-memory state, UserDefaults preferences, file documents or SwiftData models - and justify the choice
- Read and write small preferences with UserDefaults, using namespaced keys and typed accessors, and explain why it must not be used as a database
- Define persistent model classes with the @Model macro and set up a ModelContainer with the .modelContainer modifier so views receive a model context
- Build a full CRUD screen with @Query live results, context.insert and context.delete, mutating fetched models to update them
- Filter and sort fetches with #Predicate and SortDescriptor, and describe how schema versioning and lightweight migration keep shipped stores loadable