← All daysDay 30 of 49 · Part 8: Data, persistence, and networking
Day 30

SwiftData

These are the lesson notes for this day. Its build-along tutorial and flash cards have not been written yet.

Lesson 34

SwiftData

SwiftData stores your model objects on disk. Mark a class @Model, add .modelContainer(for:) to your app's scene, and fetch in a view with @Query, which keeps the view up to date as the data changes. You insert, delete, and save through a ModelContext, which you get from @Environment(\.modelContext). Relationships, sorting, and filtering with #Predicate are built in.

Coming from UIKit, SwiftData is the successor to Core Data, and @Query does the job of NSFetchedResultsController. iOS 27 adds queries divided into sections, a ResultsObserver for watching results from outside a view, and @Attribute(.codable) for storing Codable values.

Example
@Model
final class Trip {
    var name: String
    var date: Date
    init(name: String, date: Date) { self.name = name; self.date = date }
}

struct TripsScreen: View {
    @Query(sort: \Trip.date) private var trips: [Trip]      // stays current automatically
    @Environment(\.modelContext) private var context

    var body: some View {
        List(trips) { trip in Text(trip.name) }
            .toolbar {
                Button("Add") { context.insert(Trip(name: "New trip", date: .now)) }
            }
    }
}
// In the App:   WindowGroup { TripsScreen() }.modelContainer(for: Trip.self)
Exercise

Persist your trips with SwiftData: add, edit, delete, and sort them. Then quit and relaunch the app and confirm the data is still there.

After this lesson you should be able to answer
  1. Which three pieces do you need in order to show persisted data in a view?
  2. How does @Query keep a view up to date?
  3. Where do you get the ModelContext, and what do you use it for?
Resources