Project 3: To-Do App with SwiftData, Filters and Tests

iOS App Development with Swift and SwiftUI: 13 Projects · More Real-World iOS Projects · 10 min read · Updated

SwiftData round trip

  1. The user adds a task in the view.
  2. The view asks the model context to insert it.
  3. SwiftData saves it to the store on the phone.
  4. @Query notices the change and the list redraws.

A to-do list is the standard first app with a database, because it needs the four basic operations: create, read, update and delete. SwiftData makes this short. You mark a class with @Model, give the app a model container, and a @Query in the view always shows the current rows. When a task changes, the screen changes, and when the app is closed the tasks stay.

This project also shows how to test SwiftData without touching real data. A test creates a container that lives only in memory, so each test starts empty and leaves nothing behind.

Concepts in this project

  • @Model: turns a class into a stored type. Plain properties become saved columns.
  • modelContainer(for:): set once on the scene. It creates the store and gives every view a model context.
  • @Query: a property wrapper that fetches and keeps the list updated, with sorting built in.
  • Insert, change, delete: context.insert, setting a property such as isDone, and context.delete. SwiftData saves automatically.
  • A filter enum: TodoFilter.apply(to:) keeps the filtering rule in one testable place.
  • In-memory test store: ModelConfiguration(isStoredInMemoryOnly: true).

Create the project

  1. In Xcode choose File > New > Project > iOS > App. Set Interface to SwiftUI, Language to Swift, and Testing System to Swift Testing. Set the minimum deployment to iOS 17, because the code uses @Observable. Name the product Todo.
  2. Delete the default ContentView.swift and the default @main file, then add the files below.
Todo/
  TodoApp.swift       @main with modelContainer
  TodoItem.swift      @Model and TodoFilter
  TodoListView.swift  add, list, toggle, delete
TodoTests/
  TodoTests.swift

The code

`TodoItem.swift`

import Foundation
import SwiftData

@Model
final class TodoItem {
    var title: String
    var isDone: Bool
    var createdAt: Date

    init(title: String, isDone: Bool = false, createdAt: Date = .now) {
        self.title = title
        self.isDone = isDone
        self.createdAt = createdAt
    }
}

enum TodoFilter: String, CaseIterable, Identifiable {
    case all = "All"
    case open = "Open"
    case done = "Done"

    var id: String { rawValue }

    func apply(to items: [TodoItem]) -> [TodoItem] {
        switch self {
        case .all: return items
        case .open: return items.filter { !$0.isDone }
        case .done: return items.filter { $0.isDone }
        }
    }
}

`TodoListView.swift`

import SwiftUI
import SwiftData

struct TodoListView: View {
    @Environment(\.modelContext) private var context
    @Query(sort: \TodoItem.createdAt, order: .reverse) private var items: [TodoItem]

    @State private var newTitle = ""
    @State private var filter: TodoFilter = .all

    private var canAdd: Bool {
        !newTitle.trimmingCharacters(in: .whitespaces).isEmpty
    }

    var body: some View {
        NavigationStack {
            List {
                Section {
                    HStack {
                        TextField("New task", text: $newTitle)
                            .onSubmit(add)
                        Button("Add", action: add)
                            .disabled(!canAdd)
                    }
                    Picker("Show", selection: $filter) {
                        ForEach(TodoFilter.allCases) { option in
                            Text(option.rawValue).tag(option)
                        }
                    }
                    .pickerStyle(.segmented)
                }

                Section {
                    let shown = filter.apply(to: items)
                    if shown.isEmpty {
                        Text("Nothing here yet.")
                            .foregroundStyle(.secondary)
                    }
                    ForEach(shown) { item in
                        Button {
                            item.isDone.toggle()
                        } label: {
                            HStack {
                                Image(systemName: item.isDone ? "checkmark.circle.fill" : "circle")
                                Text(item.title)
                                    .strikethrough(item.isDone)
                                    .foregroundStyle(item.isDone ? .secondary : .primary)
                            }
                        }
                        .buttonStyle(.plain)
                    }
                    .onDelete(perform: delete)
                }
            }
            .navigationTitle("To-Do")
        }
    }

    private func add() {
        guard canAdd else { return }
        context.insert(TodoItem(title: newTitle.trimmingCharacters(in: .whitespaces)))
        newTitle = ""
    }

    private func delete(at offsets: IndexSet) {
        let shown = filter.apply(to: items)
        for index in offsets {
            context.delete(shown[index])
        }
    }
}

`TodoApp.swift`

import SwiftUI
import SwiftData

@main
struct TodoApp: App {
    var body: some Scene {
        WindowGroup {
            TodoListView()
        }
        .modelContainer(for: TodoItem.self)
    }
}

`TodoTests.swift (in the tests target)`

import Testing
import SwiftData
@testable import Todo

struct TodoTests {
    private func makeContext() throws -> ModelContext {
        let config = ModelConfiguration(isStoredInMemoryOnly: true)
        let container = try ModelContainer(for: TodoItem.self, configurations: config)
        return ModelContext(container)
    }

    @Test func savedItemsComeBack() throws {
        let context = try makeContext()
        context.insert(TodoItem(title: "Buy milk"))
        context.insert(TodoItem(title: "Call Asha", isDone: true))
        try context.save()

        let all = try context.fetch(FetchDescriptor<TodoItem>())
        #expect(all.count == 2)
    }

    @Test func filterSeparatesOpenAndDone() {
        let items = [TodoItem(title: "A"), TodoItem(title: "B", isDone: true)]
        #expect(TodoFilter.open.apply(to: items).map(\.title) == ["A"])
        #expect(TodoFilter.done.apply(to: items).map(\.title) == ["B"])
        #expect(TodoFilter.all.apply(to: items).count == 2)
    }
}

Walkthrough

TodoItem is a final class with three properties. The initialiser gives isDone and createdAt default values, so creating a task needs only a title. @Model is a macro, so you do not write any storage code yourself.

In TodoListView, @Environment(\.modelContext) gives the view the context it uses to insert and delete. @Query(sort: \TodoItem.createdAt, order: .reverse) returns the newest tasks first. Because the wrapper observes the store, you never refresh the list by hand.

The add function trims spaces, ignores empty titles, inserts a new item and clears the text field. The same function is used by the Add button and by pressing return, through onSubmit. Reusing one function keeps both paths identical.

Delete needs care. Swipe-to-delete gives you positions in the list that is shown, which may be filtered, not positions in the full list. So delete(at:) applies the filter again and deletes the items at those positions in the filtered list. Using the unfiltered list here would delete the wrong task, which is a classic bug.

The tests build a container with isStoredInMemoryOnly: true, save two items and fetch them back. The second test checks the filter without a database at all, because TodoFilter.apply is a plain function over an array.

How it works

  • The scene's modelContainer(for: TodoItem.self) creates the store and shares a context with every view.
  • @Query fetches the items sorted by date, and redraws the list whenever they change.
  • Tapping a row toggles isDone. Because the item is a model object, the change is saved.
  • The segmented picker changes filter, and the list shows filter.apply(to: items).

Expected output

The screen shows a text box with an Add button, a segmented control with All, Open and Done, and a message "Nothing here yet." Type "Buy milk" and press Add: it appears with an empty circle. Tap it: the circle fills and the text is crossed out. Choose Open: it disappears from the list. Swipe a row left and delete it. Quit the app from the app switcher and open it again: the remaining tasks are still there. Both tests pass.

Your task

  1. Build the app, add five tasks and mark two done.
  2. Add a due date property and sort by it. Watch what happens to saved data when you change the model, then read lesson 12 again.
  3. Add a search field with .searchable that filters by title.
  4. Write a test that checks the order of @Query results with a FetchDescriptor and a sort.

How to check it worked

  • Tasks survive closing the app.
  • Delete removes the task you swiped, even with a filter on.
  • The tests use an in-memory store.

Next, try the same idea on another platform with the Android Development with Kotlin course, or go deeper on iOS with the Advanced iOS Development course.

Frequently asked questions

Do I call save() myself?

SwiftData saves automatically at sensible moments. You can call try context.save() when you need it saved at an exact time, as the test does.

Why test with an in-memory store?

Each test starts empty and leaves nothing on disk, so tests are fast and cannot affect each other or your real data.

What happens if I change the model later?

Adding a property with a default usually works. For other changes you need a migration, which the advanced iOS course covers.