Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 46 ยท Projects

Project: A To-Do App

Build a SwiftUI to-do app step by step: model, list, add, complete and delete, state design and saving to disk with Codable. The logic runs here; the UI is shown read-only.

A to-do app is the classic first project because it exercises almost everything small apps need: a model, a list, user input, changes to the data and saving it between launches. In this project you will design the model and the store first, test the logic, and then connect it to SwiftUI views.

Xcode cannot run on this site, so the work is split on purpose. The logic (model, store, filtering and Codable persistence) is plain Swift and runs here on Piston. The views are shown as read-only SwiftUI code that you type into a new Xcode project (iOS 17 or later). The pieces refer to earlier lessons: state and binding, @Observable, lists and files.

What we are building

Add Type a title, press return.
Complete Tap the circle to check it off.
Delete Swipe a row away.
Remember Reopen the app and the list is still there.
1 / 2

Step 1: the model

Each item needs a stable identity (so SwiftUI can track rows), a title, and a done flag. Making it Identifiable and Codable costs two words and pays for lists and saving.

Swift
// read-only: Models/TodoItem.swift
import Foundation

struct TodoItem: Identifiable, Codable, Equatable {
    var id = UUID()
    var title: String
    var isDone = false
}

A UUID for the id means two items with the same title never collide, and renaming an item does not change its identity. Beware of using the title as the id; that breaks the moment two tasks share a name.

Step 2: the store

State design is the heart of this project. There should be one source of truth: a store object that owns the array. Views read from it and call its methods; they never edit the array directly. That keeps rules (like "ignore empty titles") in one place.

The stand-in below is the real store logic, minus the @Observable macro and the UI, so it runs on Piston. Everything marked with the comment would be identical in your app.

Swift The to-do store

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.

Check how add rejects blank input and trims spaces, how toggle finds the item by id rather than by position (positions change when a filter is applied), and how remaining is derived from items instead of being stored as a second number that could drift out of sync. Never store what you can compute.

Why the id, not the index

The row the user taps is a position in the filtered list. If you toggled items[rowIndex], completing a row while viewing "Open" would flip the wrong item. Passing the id makes the action correct whatever view the row came from.

Step 3: saving with Codable

For a small list, a JSON file in the app's Documents folder is simple and robust. JSONEncoder turns the array into Data, and Data.write(to:) saves it; loading reverses the steps. The stand-in below does a round trip in memory, then through a real temporary file, and shows the safe handling of a missing or corrupt file.

Swift Saving and loading with Codable

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.

Two habits are worth copying: .atomic writes to a temporary file and swaps it in, so a crash mid-save cannot leave half a file, and load never crashes on a missing or damaged file. A user should never lose the app because of one bad save. When the data grows, large, or needs queries and relationships, move to SwiftData.

Step 4: connect the store to SwiftUI

On a real device, the store becomes an @Observable class so views update when it changes. It saves after every mutation.

Swift
// read-only: Store/TodoStore.swift
import Foundation
import Observation

@Observable
final class TodoStore {
    private(set) var items: [TodoItem] = []
    private let fileURL: URL

    init(fileURL: URL = URL.documentsDirectory.appending(path: "todos.json")) {
        self.fileURL = fileURL
        if let data = try? Data(contentsOf: fileURL),
           let saved = try? JSONDecoder().decode([TodoItem].self, from: data) {
            items = saved
        }
    }

    func add(_ title: String) {
        let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return }
        items.append(TodoItem(title: trimmed))
        save()
    }

    func toggle(_ item: TodoItem) {
        guard let index = items.firstIndex(of: item) else { return }
        items[index].isDone.toggle()
        save()
    }

    func delete(at offsets: IndexSet) {
        items.remove(atOffsets: offsets)
        save()
    }

    private func save() {
        guard let data = try? JSONEncoder().encode(items) else { return }
        try? data.write(to: fileURL, options: .atomic)
    }
}

Next, the views. The root view owns the store with @State (the modern way for @Observable classes), holds the text field's draft in a separate @State, and passes the store down.

Swift
// read-only: Views/ContentView.swift
import SwiftUI

struct ContentView: View {
    @State private var store = TodoStore()
    @State private var draft = ""
    @State private var filter = Filter.all

    var body: some View {
        NavigationStack {
            List {
                Section {
                    TextField("New task", text: $draft)
                        .onSubmit(addDraft)
                        .submitLabel(.done)
                }
                Section("\(store.remaining) left") {
                    ForEach(store.visible(filter)) { item in
                        TodoRow(item: item) { store.toggle(item) }
                    }
                    .onDelete { store.delete(at: $0) }
                }
            }
            .navigationTitle("To-Do")
            .toolbar {
                Picker("Filter", selection: $filter) {
                    ForEach(Filter.allCases, id: \.self) { Text($0.rawValue.capitalized) }
                }
                .pickerStyle(.segmented)
            }
        }
    }

    private func addDraft() {
        store.add(draft)
        draft = ""
    }
}

struct TodoRow: View {
    let item: TodoItem
    let onToggle: () -> Void

    var body: some View {
        Button(action: onToggle) {
            Label(item.title, systemImage: item.isDone ? "checkmark.circle.fill" : "circle")
                .strikethrough(item.isDone)
                .foregroundStyle(item.isDone ? .secondary : .primary)
        }
        .buttonStyle(.plain)
    }
}

There is one wrinkle: .onDelete on a filtered list reports offsets inside the filtered array, not the whole array. For a polished app, map those offsets to ids first (let ids = offsets.map { visible[$0].id }) and delete by id. That is the same lesson as the toggle: identity beats position. Also, Filter and visible(_:) here match the stand-in above, so you can paste both without changes.

Ideas to extend it

  • Add a dueDate: Date? to TodoItem. Because the decoding of the new property would fail on old files, give it a default and make it optional.
  • Add an Edit button using EditButton() and drag-to-reorder with .onMove.
  • Move the model into SwiftData, using @Model and @Query, and compare how much code disappears.
  • Write tests for TodoStore with a temporary file URL, as described in Testing View Models and UI.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the store toggle items by id instead of by row index?

    A tapped row's position belongs to the filtered list. The id always identifies the same item.
  2. 2. What is the best way to track how many tasks are still open?

    A derived value cannot go out of sync with the data it comes from. Store the data, compute the summary.
  3. 3. What does .atomic do when writing the file?

    An atomic write keeps either the complete old file or the complete new file, never a partial one.
  4. 4. Which types must TodoItem conform to for the list and for saving?

    Identifiable lets ForEach track rows; Codable lets JSONEncoder and JSONDecoder save and restore the array.

Summary

  • Build logic first: a Codable, Identifiable model and a store that owns the array and enforces the rules.
  • Keep one source of truth; derive counts and filtered lists instead of storing copies.
  • Act on items by id, not by row position, especially in filtered lists.
  • Save as JSON with atomic writes, and make loading tolerant of missing or corrupt files.
  • In SwiftUI, own an @Observable store with @State at the root and keep text-field drafts in their own state.
  • When the data outgrows a JSON file, move to SwiftData.

Next: Project: A Weather App with Networking