Local Data Persistence

Article · 2:00

UserDefaults for preferences, SwiftData for a model that has to be queried.

There are two kinds of saved data and using the wrong tool for either is a familiar mistake. UserDefaults is a small property list for preferences: which tab was open, whether the reader has seen the onboarding, their chosen sort order. It is not a database, it is loaded into memory whole, and putting a few thousand records in it will make your app slow to launch. In SwiftUI, @AppStorage reads and writes it with one line and redraws the view when the value changes.

SwiftData is the modern persistence framework, built on Core Data but with the ceremony removed. Annotate a class with @Model, add a .modelContainer to your app, and you have a saved, queryable, relational store. @Query fetches into a view and keeps it up to date as rows change. Core Data is still there underneath and is still what you use for the cases SwiftData does not cover yet - but new code starts with SwiftData.

Neither belongs in your view. Keep the persistence calls behind a type you can swap, so a test can run against an in-memory container rather than the real database - SwiftData supports exactly that with one configuration flag.

import SwiftUI
import SwiftData

// A preference: one value, read and written in a line.
struct SettingsRow: View {
    @AppStorage("sortNewestFirst") private var newestFirst = true
    var body: some View {
        Toggle("Newest first", isOn: $newestFirst)
    }
}

// A model: a class the framework persists and can query.
@Model
final class Note {
    var title: String
    var body: String
    var createdAt: Date
    var isPinned: Bool

    init(title: String, body: String = "", isPinned: Bool = false) {
        self.title = title
        self.body = body
        self.createdAt = .now
        self.isPinned = isPinned
    }
}

struct NotesList: View {
    // @Query fetches and stays live as rows are inserted or deleted.
    @Query(sort: \Note.createdAt, order: .reverse) private var notes: [Note]
    @Environment(\.modelContext) private var context

    var body: some View {
        List {
            ForEach(notes) { note in
                Text(note.title)
            }
            .onDelete { indexes in
                for index in indexes { context.delete(notes[index]) }
            }
        }
        .toolbar {
            Button("Add") { context.insert(Note(title: "Untitled")) }
        }
    }
}

@main
struct NotesApp: App {
    var body: some Scene {
        WindowGroup { NotesList() }
            .modelContainer(for: Note.self)
    }
}