Skip to content
Tutorials Center
My learning

Topics

Lesson 126 of 146 ยท Platforms and Ecosystem

SwiftData and Persistence Overview

Compare Swift persistence options and learn SwiftData - @Model, ModelContainer, ModelContext, @Query, relationships and migration - with runnable Predicate and context stand-ins and Core Data notes.

Almost every real app has to remember things after it closes: a to-do list, a reading history, a shopping cart, a setting. Keeping data in variables only lasts until the process ends. Persistence means writing the data somewhere that survives, then reading it back, and doing it in a way that stays fast and correct when there are thousands of records and the app changes from one version to the next.

Apple's current answer is SwiftData, a framework for describing your model types in plain Swift and letting the system store, query and migrate them. The framework itself needs an Apple platform, so the SwiftData listings in this lesson are read-only. But the ideas are not locked to Apple: this page shows runnable Swift for the parts that do work here (Codable storage, the real #Predicate macro and sort descriptors) and builds a small stand-in for the context, so you understand what the real one does. It builds on Codable, JSON, macros and key paths.

The persistence options

There is no single best way to store data. The right choice depends on how much data you have and what you do with it.

flowchart TD
    Q{"What are you storing?"}
    Q -->|"A few small settings"| UD["UserDefaults / AppStorage"]
    Q -->|"One document or a small list"| FILE["Codable value written to a file"]
    Q -->|"Many records you filter, sort, relate"| DB["Database layer"]
    DB --> SD["SwiftData (modern, macro based)"]
    DB --> CD["Core Data (older, very capable)"]
    DB --> SQL["SQLite directly or a third-party library"]
    Q -->|"Secrets such as tokens"| KC["Keychain"]

Match the tool to the shape of the data; databases pay off when you query and relate records.

For small data the simplest solution is the best one: encode a Codable value to JSON and write it to a file. You already know the pieces, so here is the whole round trip in memory (a real app would write data to a file with write(to:), see files and I/O):

Swift Persisting a Codable value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

That is perfect for hundreds of items. It starts to hurt when the list is large (you load and rewrite everything for a tiny change), when you need to find "all unfinished tasks due this week" without loading all of them, or when records refer to each other. A database solves exactly those problems, and SwiftData is the database layer designed for Swift.

SwiftData in one picture

SwiftData has four pieces you must know:

Piece Role
@Model class Your data type. The macro makes it persistable and observable.
ModelContainer The storage: it knows your model types and where the data lives (disk, memory, iCloud).
ModelContext A scratch pad of changes: insert, delete, edit, fetch, then save.
@Query / FetchDescriptor How you ask for records with a filter and a sort order.
flowchart LR
    V["SwiftUI view<br/>@Query"] --> C["ModelContext<br/>(unsaved changes)"]
    C -->|"save()"| K["ModelContainer"]
    K --> S[("Store on disk")]
    S -->|"fetch"| C

The context sits between your code and the store: you change objects in the context and save() writes the batch.

Defining models (read-only)

A model is a class marked @Model. Plain stored properties of Codable-like types (strings, numbers, dates, arrays, enums, structs) become stored attributes; properties that hold other models become relationships.

Swift
// Read-only example: needs SwiftData and an Apple platform.
import SwiftData
import Foundation

@Model
final class Trip {
    @Attribute(.unique) var name: String
    var startDate: Date
    var notes: String = ""

    @Relationship(deleteRule: .cascade, inverse: \Stop.trip)
    var stops: [Stop] = []

    @Transient var isExpanded = false    // not stored

    init(name: String, startDate: Date) {
        self.name = name
        self.startDate = startDate
    }
}

@Model
final class Stop {
    var city: String
    var order: Int
    var trip: Trip?                      // the other side of the relationship

    init(city: String, order: Int) {
        self.city = city
        self.order = order
    }
}

What the attributes mean:

  • @Attribute(.unique) makes the value unique; inserting a second Trip with the same name updates the existing one (an "upsert"). Other options include .externalStorage for large blobs and .spotlight.
  • @Relationship(deleteRule:inverse:) describes how two models connect. .cascade deletes the stops when the trip goes, .nullify (the default) just clears the link, .deny blocks deletion while children exist.
  • @Transient keeps a property out of the store.
  • The macro also makes the class Observable (see Observation), which is why SwiftUI updates when a model changes.

Enums and Codable structs work as properties; relationships should be optional or have a default (an empty array), and models need a designated init.

The container, the context and saving (read-only)

You create one container for the app and let SwiftUI hand a context to views through the environment:

Swift
// Read-only example: needs SwiftData, SwiftUI and an Apple platform.
import SwiftUI
import SwiftData

@main
struct TravelApp: App {
    var body: some Scene {
        WindowGroup {
            TripListView()
        }
        .modelContainer(for: [Trip.self, Stop.self])    // stored on disk by default
    }
}

struct TripListView: View {
    @Environment(\.modelContext) private var context
    @Query(sort: \Trip.startDate, order: .reverse) private var trips: [Trip]

    var body: some View {
        List {
            ForEach(trips) { trip in
                Text(trip.name)
            }
            .onDelete { offsets in
                for index in offsets { context.delete(trips[index]) }
            }
        }
        .toolbar {
            Button("Add") {
                context.insert(Trip(name: "New trip", startDate: .now))
            }
        }
    }
}

@Query is observable: when the context inserts or deletes a trip, the list updates itself. SwiftData autosaves the main context at sensible moments, and you can call try context.save() to force it (for example before the app quits). In tests and previews, create a container in memory so nothing touches the disk:

Swift
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(for: Trip.self, Stop.self, configurations: config)
let context = ModelContext(container)

Querying: predicates and sort descriptors

A query is a predicate (which records) plus sort descriptors (in what order). Both are ordinary Swift: #Predicate is a macro that turns a closure into a structured, inspectable filter, so the framework can translate it to database queries instead of loading everything.

The Predicate type and SortDescriptor are in Foundation itself, so they run here. The following example filters and orders plain Swift values with the same macro that SwiftData uses:

Swift #Predicate and SortDescriptor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first filter keeps the books that cost under 30 and whose title contains a capital S, which are Swift Basics and Sails and Seas. The second one, with a captured minYear, keeps one book that is recent and tagged swift. The sort descriptors reuse key paths and combine like "order by year, then title".

In SwiftData the same pieces go into a FetchDescriptor or straight into @Query:

Swift
// Read-only example: needs SwiftData.
var descriptor = FetchDescriptor<Trip>(
    predicate: #Predicate { $0.startDate > cutoff && $0.name.contains("Alps") },
    sortBy: [SortDescriptor(\.startDate)]
)
descriptor.fetchLimit = 20
let trips = try context.fetch(descriptor)
let count = try context.fetchCount(FetchDescriptor<Trip>())

// In a view, with a dynamic filter:
// @Query(filter: #Predicate<Trip> { $0.name.contains("Alps") }, sort: \Trip.name)

A SwiftData predicate can only use operations the store can translate. Things like calling your own functions inside the closure are rejected at build or run time. Keep predicates to comparisons, contains, &&, ||, ! and simple key paths.

What the context really does: a stand-in

The context is a unit of work: it collects inserts and deletes in memory, lets you query a view of the world that includes them, and only writes everything when you save. This small stand-in has the same shape. It stores records as JSON, which plays the role of the file on disk. It is not SwiftData, just the same idea in a few dozen lines.

Swift A tiny ModelContext stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Watch the order of events. The inserts are visible to fetch before save, and hasChanges is true. After save the changes are written (the JSON). A delete is also visible immediately, but the saved bytes still contain the note until the next save, which is why the "saved copy" still counts three records. The relaunch decodes the new bytes and sees only the two notes that remain.

Real SwiftData does a lot more: it records exactly which properties changed, tracks relationships, writes to SQLite with transactions, loads objects lazily and handles several contexts, but the mental model is this one.

Threads, actors and background work

ModelContext is not Sendable: do not pass a context or a model object from one thread to another. The main context (from the environment) belongs to the main actor. For heavy imports, create a separate context on a background executor with the @ModelActor macro, and pass only PersistentIdentifier values between actors, then re-fetch the object by identifier in the receiving context. This is the same discipline as with any non-Sendable state (see Sendable and actors).

Changing your models: migration

Version 2 of an app often changes the model: a new property, a rename, a split. SwiftData handles simple changes (adding an optional property or one with a default) automatically. For others you describe versions:

Swift
// Read-only example: needs SwiftData.
enum SchemaV1: VersionedSchema {
    static var versionIdentifier = Schema.Version(1, 0, 0)
    static var models: [any PersistentModel.Type] { [SchemaV1.Trip.self] }
    @Model final class Trip { var name: String; init(name: String) { self.name = name } }
}

enum SchemaV2: VersionedSchema {
    static var versionIdentifier = Schema.Version(2, 0, 0)
    static var models: [any PersistentModel.Type] { [SchemaV2.Trip.self] }
    @Model final class Trip {
        @Attribute(originalName: "name") var title: String      // a rename
        var isFavorite = false                                  // new, with a default
        init(title: String) { self.title = title }
    }
}

enum TravelMigration: SchemaMigrationPlan {
    static var schemas: [any VersionedSchema.Type] { [SchemaV1.self, SchemaV2.self] }
    static var stages: [MigrationStage] {
        [.lightweight(fromVersion: SchemaV1.self, toVersion: SchemaV2.self)]
    }
}

A lightweight stage covers additions, removals and renames declared with originalName. A custom stage lets you run code before and after for transformations. Test migrations with a copy of real old data: they are the most common source of data-loss bugs.

Core Data, the older sibling (read-only)

SwiftData is built on top of Core Data, which has existed since 2005. You will meet Core Data in older apps and in cases SwiftData does not cover. It uses a visual model file (.xcdatamodeld) and NSManagedObject subclasses instead of macros:

Swift
// Read-only example: needs Core Data and an Apple platform.
import CoreData

let container = NSPersistentContainer(name: "Travel")
container.loadPersistentStores { _, error in
    if let error { fatalError("Store failed: \(error)") }
}

let context = container.viewContext                  // main-thread context
let request = NSFetchRequest<NSManagedObject>(entityName: "Trip")
request.predicate = NSPredicate(format: "name BEGINSWITH %@", "Alps")
request.sortDescriptors = [NSSortDescriptor(key: "startDate", ascending: false)]
let trips = try context.fetch(request)

container.performBackgroundTask { background in
    // Work with a private-queue context here, then:
    try? background.save()
}
Concept Core Data SwiftData
Model definition .xcdatamodeld file @Model Swift class
Storage object NSPersistentContainer ModelContainer
Scratch pad NSManagedObjectContext ModelContext
Query NSFetchRequest and string NSPredicate FetchDescriptor and type-checked #Predicate
In the view @FetchRequest @Query

Both can use the same SQLite store file. New apps that target recent OS versions should start with SwiftData, and large existing Core Data apps can adopt it gradually.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which approach is the best fit for storing a user's three small preferences?

    A few small values do not need a database. UserDefaults is the simple, built-in choice.
  2. 2. What does ModelContext.save() do in SwiftData?

    The context collects changes in memory. Saving commits the batch to the container's store.
  3. 3. What does @Relationship(deleteRule: .cascade) on a trip's stops do?

    Cascade propagates the delete to the related objects. Nullify only clears the link and deny blocks the delete.
  4. 4. Why is #Predicate preferred over a plain closure in a SwiftData fetch?

    A predicate is data that can be inspected and translated; a plain closure is opaque, so everything would need to be loaded first.
  5. 5. Can you pass a ModelContext to a background task on another thread?

    ModelContext and model objects are not Sendable. Pass PersistentIdentifier values and re-fetch in the other context.

Summary

  • Pick the simplest store that fits: UserDefaults for settings, a Codable file for small documents, a database when you query and relate many records.
  • SwiftData describes models with @Model classes, stores them in a ModelContainer and edits them through a ModelContext that you save().
  • @Query and FetchDescriptor take a #Predicate plus sort descriptors; both come from Foundation and work on plain Swift values too.
  • Relationships carry delete rules; @Attribute(.unique) upserts; @Transient skips storage.
  • Contexts and models are not Sendable: use a context per actor and pass identifiers.
  • Declare schema versions and a migration plan before you ship a model change.
  • Core Data is the older engine underneath, with an NSManagedObjectContext and NSFetchRequest API you will still meet in existing apps.

Next: Observation and @Observable