Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 46 ยท Projects

Project: A Notes App with SwiftData

Build a notes app with SwiftData: model design, @Query sorting and search, pinned notes, a detail screen with navigation and deletion. Includes a runnable model stand-in.

A notes app is a good way to learn SwiftData because notes are naturally a collection of records: you create them, edit them in place, sort them, search them and delete them. Unlike the to-do project, you will not write any file-saving code. SwiftData stores the objects and tells your views when they change.

SwiftData needs Xcode, so the framework code here is read-only; type it into a new iOS 17+ project (check "Use SwiftData" is not needed, you will add it yourself). Its sorting, filtering and grouping rules, however, are ordinary logic that you can see running: two stand-ins on Piston mimic what @Query does with sort descriptors and predicates. The ideas build on SwiftData Basics and NavigationStack.

What the app does

Create Add a note, edit it in place.
Pin Pinned notes stay on top.
Search Filter by title or body.
Delete Swipe in the list or from the detail.
1 / 2

Step 1: design the model

Think about what a note is before you write code. Each note has text the user wrote, a few timestamps and a pin flag. Keep the title and body separate so the list can show one line and a preview.

Swift
// read-only: Models/Note.swift
import Foundation
import SwiftData

@Model
final class Note {
    var title: String
    var body: String
    var isPinned: Bool
    var createdAt: Date
    var updatedAt: Date

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

@Model is a class, not a struct, because SwiftData tracks changes to a shared object. SwiftData also generates the identity for you. Give every property a default or set it in init, and prefer simple types (strings, numbers, dates, booleans, arrays of those, enums that are Codable) for stored properties. For relationships such as folders that contain notes, see the end of this lesson.

Set up the container once, where the app starts:

Swift
// read-only: NotesApp.swift
import SwiftUI
import SwiftData

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

.modelContainer(for:) creates the store on disk and puts its model context in the environment for every view below.

Step 2: sorting and searching, in logic first

A @Query declares which notes a view wants and in what order. Before you use it, practice the same rules on plain values, where you can run and test them. The business rules for this app are:

  1. Pinned notes come first.
  2. Within each group, the most recently edited comes first.
  3. Search matches the title or body, ignoring case and accents, and ignores blank queries.
Swift Sort and search rules for notes

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.

Notice that "CAFE" finds "Cafรฉ beans" in one note and "cafe budget" in another: case and accent differences vanish with the right comparison options. In SwiftData, predicates are compiled for the database, so localizedStandardContains is the usual choice for user-facing search.

Step 3: the list with @Query

Now the real thing. @Query takes sort descriptors; because you want pinned first, then newest, pass two of them. For search, a predicate depends on user input, so the view builds its query in init.

Swift
// read-only: Views/NoteListView.swift
import SwiftUI
import SwiftData

struct NoteListView: View {
    @Environment(\.modelContext) private var context
    @State private var searchText = ""
    @State private var path = [Note]()

    var body: some View {
        NavigationStack(path: $path) {
            NoteResults(searchText: searchText, onSelect: { path.append($0) })
                .navigationTitle("Notes")
                .searchable(text: $searchText)
                .toolbar {
                    Button("New Note", systemImage: "square.and.pencil", action: addNote)
                }
                .navigationDestination(for: Note.self) { NoteDetailView(note: $0) }
        }
    }

    private func addNote() {
        let note = Note()
        context.insert(note)
        path.append(note)       // open the editor right away
    }
}

struct NoteResults: View {
    @Environment(\.modelContext) private var context
    @Query private var notes: [Note]
    let onSelect: (Note) -> Void

    init(searchText: String, onSelect: @escaping (Note) -> Void) {
        self.onSelect = onSelect
        let sort = [SortDescriptor(\Note.isPinned, order: .reverse),
                    SortDescriptor(\Note.updatedAt, order: .reverse)]
        if searchText.isEmpty {
            _notes = Query(sort: sort)
        } else {
            _notes = Query(
                filter: #Predicate<Note> {
                    $0.title.localizedStandardContains(searchText)
                        || $0.body.localizedStandardContains(searchText)
                },
                sort: sort
            )
        }
    }

    var body: some View {
        List {
            ForEach(notes) { note in
                Button { onSelect(note) } label: {
                    VStack(alignment: .leading, spacing: 4) {
                        HStack {
                            if note.isPinned { Image(systemName: "pin.fill").foregroundStyle(.orange) }
                            Text(note.title.isEmpty ? "Untitled" : note.title).font(.headline)
                        }
                        Text(note.body).lineLimit(2).foregroundStyle(.secondary)
                    }
                }
                .buttonStyle(.plain)
            }
            .onDelete { offsets in
                for index in offsets { context.delete(notes[index]) }
            }
        }
        .overlay {
            if notes.isEmpty { ContentUnavailableView.search }
        }
    }
}

Three things to learn from this code. First, the query is rebuilt whenever searchText changes, because NoteResults.init runs again with the new value. Second, the sort order is data, not a loop in the view: SwiftData sorts in the database. Third, context.insert and context.delete are all it takes to change the store, and every @Query on screen updates by itself.

The empty overlay says "no results" but would also show for a brand-new, empty database. Real apps distinguish the two: show an invitation to write the first note when the store is empty and no search is active.

Step 4: the detail screen

The editor binds straight to the model object. Because Note is observable, typing updates the stored object immediately, and SwiftData autosaves.

Swift
// read-only: Views/NoteDetailView.swift
import SwiftUI
import SwiftData

struct NoteDetailView: View {
    @Bindable var note: Note
    @Environment(\.modelContext) private var context
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        Form {
            TextField("Title", text: $note.title)
            Toggle("Pinned", isOn: $note.isPinned)
            TextEditor(text: $note.body)
                .frame(minHeight: 240)
        }
        .navigationTitle(note.title.isEmpty ? "New Note" : note.title)
        .navigationBarTitleDisplayMode(.inline)
        .onChange(of: note.title) { note.updatedAt = .now }
        .onChange(of: note.body) { note.updatedAt = .now }
        .toolbar {
            Button("Delete", systemImage: "trash", role: .destructive) {
                context.delete(note)
                dismiss()
            }
        }
    }
}

@Bindable produces $note.title bindings from an observable object (@Observable and Observation explains why). The onChange handlers stamp updatedAt, which moves the note to the top of its group, matching rule 2.

Step 5: a sectioned list, in logic

Many notes apps show "Pinned" and "Earlier" sections. Grouping is another rule you can test before drawing it:

Swift Grouping notes into sections

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.

In SwiftUI you would loop over order and show a Section(name) for each non-empty group. Because grouping needs the whole result set, it is done in Swift after the query rather than inside the predicate.

Where to go next

  • Folders: add @Relationship(deleteRule: .cascade) var notes: [Note] to a Folder model, and var folder: Folder? on Note. Deleting a folder then deletes its notes.
  • Previews: build an in-memory container (ModelConfiguration(isStoredInMemoryOnly: true)) filled with sample notes so every preview has data.
  • Migrations: adding a property with a default value is a lightweight change; renaming or splitting properties needs a versioned schema (SwiftData Basics gives an overview).
  • Sync: turning on iCloud means the model must have no unique constraints and all properties optional or defaulted (Core Data, CloudKit and Sync).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is Note declared as a class with @Model?

    A stored record has an identity and is edited in place, so SwiftData uses reference types that it can observe and persist.
  2. 2. How do you get the list to show pinned notes first, then the newest?

    Sort descriptors are applied in order by the store: pinned first, ties broken by newest.
  3. 3. What makes the search results update as the user types?

    The query is created in init from the search text; when the parent passes a new value, a new query runs.
  4. 4. Why does NoteDetailView use @Bindable?

    @Bindable lets you write $note.property for controls, while the model stays a reference-type observable object.

Summary

  • Model a note as a @Model class; create the container once with .modelContainer(for:).
  • @Query gives a live, sorted, filtered list; rebuild it in init when search text changes.
  • Use context.insert and context.delete; edits to model objects save and refresh queries automatically.
  • Bind editors to model properties with @Bindable; stamp updatedAt on changes.
  • Test sort, search and grouping rules as plain logic; empty-store and empty-search states deserve different messages.
  • Add folders with relationships, and use in-memory containers for previews.

Next: Project: A Habit Tracker