Back to articles

Build a Complete Native iOS App with SwiftUI and SwiftData: Twelve Steps, 85 Tests, and the Road to the App Store

Created by Manuel Herrera Mesén ·

Part 4 of 4swiftuiswiftdataiosmvvmserie-ios
Download as PDF · 174 pp.

Part 4 of 4 of the series "Native iOS Engineering".

You open Xcode, pick the app template, and a "Hello, world!" shows up in the simulator. Between that screen and an app someone would install there's a stretch no standalone example covers: saving the data, rejecting what's invalid, failing without leaving a blank screen, and having tests that guard all of it.

In this part you cover that stretch with Native Task Manager, the task app you saw at the start of the series. Twelve steps later you have an app that lists, creates, edits, completes, filters, searches, and deletes tasks, imports samples from a REST API, stores them with SwiftData, and passes 85 tests without touching the network.

Native Task Manager on an iPhone: a list of tasks with a checkbox for done, a picker to filter between all, pending, and completed, and a button to create a new task.
Native Task Manager at the end of step 12.

Time and fast track. Reading it takes about two hours; building it with Xcode open, about six. If you have 45 minutes, do step 01: your project runs in the simulator. With an hour, go on with 02 and 03, or download the step 02 zip and do only 03. Every step comes with its zip, so you can pick up from any of them.

At the end you'll find how to get the app onto your iPhone and into the App Store and the interview questions about the app.

By the end of this part you'll be able to:

  1. create a project in Swift 6 mode with iOS 18 as the minimum and explain each setting;
  2. separate the network format from the model you store, with a tested mapping;
  3. build the list, the validated form, and an injected view model;
  4. import from a REST API while showing loading, empty, success, and error;
  5. persist with SwiftData without duplicating or overwriting what the user edited;
  6. test with network-free unit tests and audited UI tests, and review the architecture;
  7. get the app onto your iPhone and into the App Store;
  8. answer the follow-up questions of an interview.
Going deeper

is iOS for you? A native app is written with the system's language and libraries, Swift and SwiftUI; a web app runs in the browser, and a cross-platform app shares code between iOS and Android. The day-to-day work in this part is that of an iOS team: deciding who owns each piece of data, showing errors well, and writing tests.

It costs you a Mac with Xcode, which is free. To install on your own iPhone, your Apple Account is enough; to publish, you need the paid membership (the final section has the details). If you like watching an app grow piece by piece and understanding why each piece sits where it does, this is for you. The full box is in part 1.

Going deeper

how to read this guide and how I verified the code. It's a guide to follow in order: each step starts from the previous one. Each one says what changes and why, shows the code, tells you what to run and what to look for (Try it yourself), and tells you about the errors that really showed up while I built it (The usual mistake).

New files are shown in full. Files that already existed are shown as a change in diff format: lines with + are added and lines with - are removed. The tests for each step go in a collapsed box, The tests for this step, with all their files. Within a step, write every file before you build: the order of the text explains, it doesn't compile. At the end of each step there's a zip with the complete project, so you can compare yours or pick up from there.

I built the app step by step, in the same order, with Xcode 27.2 (27B52) and Swift 6.4.2. Each step passed all its tests on an iPhone 17 simulator with iOS 27.2 (24B8117), created for that run and deleted at the end, and the zips were tested again one by one.

The error messages are the ones Xcode and the compiler gave, copied verbatim. The only exception is the publishing section: it's documented from the official pages, but I didn't run it, and I say so there.

Before You Start

Do you have what you need? A Mac with Xcode 27.2 and the iOS 27.2 simulator, and parts 1 to 3 read or at hand: this part doesn't repeat what an optional, an actor, or a @Model is; it links to them. You only need a network in step 07; the tests never use it.

The app's data rule, in one sentence: the sample API is only read, and after the import, the tasks are yours and live on the device.

Going deeper

the full data contract. Before writing code, it pays to decide who owns each piece of data, because that decision changes the whole design.

  • The sample API is read-only for the app. JSONPlaceholder accepts requests to create, edit, and delete, but its guide says it doesn't store them: it responds as if it had. Sending it the changes would only fake a sync.
  • After the import, the tasks are yours. Creating, editing, completing, deleting, and filtering happen only in the local SwiftData store. Nothing goes back to the API.
  • The import is idempotent. Idempotent means that repeating it leaves the same result as doing it once: each imported task keeps the identifier it had in the API, and a task whose identifier is already stored is skipped, even if you edited it. Local wins.
  • There's no sync. For two devices to see the same tasks, you'd need something else; in step 12 I tell you what.
Going deeper

how the code is split up.

Hand-drawn diagram in five rows. At the top, the views TaskListView, TaskRowView and TaskFormView, in Features. Actions go down to TaskListViewModel, @Observable and on the main actor, and state goes back up to the views. The view model depends on two protocols: TaskRepository, in Data, and TodoAPIClient, in Networking. SwiftDataTaskRepository implements TaskRepository and stores in SwiftData, with SQLite on the device: the source of truth. URLSessionTodoAPIClient and FixtureTodoAPIClient implement TodoAPIClient; the first reads JSONPlaceholder /todos?userId=1 one way only, read-only, and the second is for tests and previews, with no network. On the left, AppDependencies, in App, the composition root, with live(), inMemory() and forCurrentProcess(), creates and wires the pieces. At the bottom, Models: TaskItem, the @Model the app stores, and RemoteTodo, the DTO the network sends.
The finished app: the views only talk to the view model, and AppDependencies decides which implementation each piece gets.

It's the MVVM architecture from part 2, with a repository for the data and a client for the network. Each piece appears in a step, and I review the full map in step 12.

Going deeper

the zips, the tests, and how many each step counts. To open a zip, you unzip it and double-click NativeTaskManager.xcodeproj. You run the tests with Product › Test (⌘U); the result shows up in the Test navigator (⌘6). From the terminal, inside the project folder:

xcodebuild -project NativeTaskManager.xcodeproj -scheme NativeTaskManager \
  -destination 'platform=iOS Simulator,name=iPhone 17' test
StepWhat it addsTests
01The template project3
02The models and their mapping8
03The first screen8
04The list on SwiftData8
05The form and its validation20
06The view model and the repository35
07The network and the import47
08Loading, empty, and error54
09Persistence and caching61
10Filter, search, edit, and delete72
11UI and accessibility tests72
12Review, undoing failed saves, and audits of every screen85

A @Test with several arguments counts as one test in that total, even though it runs once per argument.

Step 01: The Project

What does a project need before the first line of code? What the Xcode template creates, with two changes. There's no command-line tool that creates an iOS project from that template: you do it in Xcode.

Creating the Project

It's the path from the lab in "Anatomy of an iOS App", with another name:

  1. File › New › Project…, iOS tab, App template, and Next.
  2. Product Name: NativeTaskManager. Organization Identifier: yours, in reverse-domain format (I used dev.example, and the app's identifier became dev.example.NativeTaskManager). Interface: SwiftUI. Language: Swift. Testing System: Swift Testing. Storage: None. Next, pick a folder, and Create.

Under Storage you leave None even though the app will use SwiftData: the SwiftData option generates a sample model, and here you write the model yourself in step 02.

The Two Changes

The Xcode 27.2 template leaves the project in Swift 5 language mode and with the newest iOS version as the minimum. You change both in the project editor: in the navigator on the left (⌘1), click the blue icon at the top, NativeTaskManager.

  1. Swift 6 mode, in all three targets. A target is a product the project builds, and this one has three: the app, NativeTaskManagerTests (the unit tests), and NativeTaskManagerUITests (the UI tests). In the TARGETS list, pick each one; in the Build Settings tab, search for "Swift Language Version" and choose Swift 6. The template sets that value in each target separately.
  2. iOS 18.0 as the minimum version, in the project. In the PROJECT list, pick NativeTaskManager; in Build Settings, search for "iOS Deployment Target" and choose iOS 18.0. The template defines it at the project level, and the three targets inherit it.

After the change, the project file ends up with these settings:

IPHONEOS_DEPLOYMENT_TARGET = 18.0                    (proyecto)
SWIFT_VERSION = 6.0                                  (los tres targets)
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor            (solo el target de la app)
SWIFT_APPROACHABLE_CONCURRENCY = YES                 (los tres targets)
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES (los tres targets)

To check them in Xcode: target › Build Settings, with All selected at the top. The search field accepts the exact name of the setting: type SWIFT_DEFAULT_ACTOR_ISOLATION and you'll see Default Actor Isolation set to MainActor only in the app target. Do the same with the others.

Why Swift 6 and Why iOS 18

Swift 6 is the language mode in which the compiler checks that there are no data races: two accesses to the same data from two threads at once, with at least one write. In Swift 5 mode those problems arrive as warnings or not at all; in Swift 6 mode they're errors. It's what you saw in "Sendable and Data Races".

iOS 18 is the oldest version the app can be installed on. The app doesn't use any API that requires iOS 18: Observation and SwiftData need iOS 17.

The policy I chose is a practice of app teams, not a technical requirement: support the current version of iOS and the two previous major ones, which today are 27, 26, and 18. On a real team, product decides it together with engineering, because it's a commitment to the people who don't update. In the code, the only thing that requires iOS 18 is a test: the fake server in step 07 uses Mutex, available since iOS 18.0.

The template's three concurrency settings are the ones from "Actors and the Main Actor":

  • SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor: everything you declare in the app target belongs to the main actor, except what you mark nonisolated or what has another explicit isolation, like an actor. The test targets don't have it, and that's why, from step 02 on, the tests that touch the model have @MainActor written on them.
  • SWIFT_APPROACHABLE_CONCURRENCY = YES: among other things, an async function that doesn't belong to any actor runs on its caller's actor. You'll notice it in step 07.
  • SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES: each file has to import the modules it uses, even if another file in the same target already imports them. You'll also notice it in step 07, with an error.

What the Template Brings

The entry point is a scene with a window that shows ContentView:

NativeTaskManager/NativeTaskManagerApp.swift
import SwiftUI
 
@main
struct NativeTaskManagerApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
NativeTaskManager/ContentView.swift
import SwiftUI
 
struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
        }
        .padding()
    }
}
 
#Preview {
    ContentView()
}

The template also brings three tests: an empty unit test, example(), in NativeTaskManagerTests/NativeTaskManagerTests.swift, and two UI tests in NativeTaskManagerUITests/NativeTaskManagerUITests.swift: testExample(), which launches the app, and testLaunchPerformance(), which measures how long it takes to start. You replace the UI tests in step 11, and there I tell you why the performance one doesn't stay.

Files and Folders

The project's folders are synchronized folders: Xcode builds whatever is inside each one, without a list of files to maintain. A file in NativeTaskManager/ goes into the app target; one in NativeTaskManagerTests/, into the test target. In the steps that follow you need three actions:

  • A new folder (Models/, Features/TaskList/…): right-click the folder that will contain it › New Folder, and type the name.
  • A Swift file: pick the folder, File › New › File from Template… (⌘N), Swift File template, and type the name.
  • A file that isn't Swift (the JSON in step 07): File › New › File from Template…, Empty File template, with its full name. To check which target a file ended up in, select it and open the File inspector (⌥⌘1), Target Membership section.

Try it yourself: pick the iPhone 17 simulator in the bar at the top and press ⌘R. Xcode builds, opens the simulator, and launches the app: a globe and "Hello, world!" in the middle. Then ⌘U: Xcode counts 3 tests, all three green in the Test navigator (⌘6).

The simulator of an iPhone 17 with the template app: a globe icon and the text Hello, world! in the middle of a white screen.
The newly created project, in the simulator.

The usual mistake: changing "Swift Language Version" only in the app target. It builds just the same, but the tests stay in Swift 5 mode, and a test with a concurrency problem passes without the compiler saying anything. Check the setting in all three targets.

Check what you learned. If the test target doesn't have SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, which actor does a function you write in a test belong to by default?

Solution

None: it's nonisolated, the language's default. The setting is per target, so what applies to the app doesn't apply to its tests. If the test touches something on the main actor, like the app's model, it has to be marked @MainActor.

What to take away: the template decides how your code compiles; the two changes (Swift 6 in all three targets, iOS 18 in the project) are yours, and the three concurrency settings come from the template.

Download the code for step 01.

Step 02: The Models

Is a task that arrives from the network the same thing as a stored task? For this app, no, and it's the first design decision:

  • RemoteTodo is what arrives from the network: an element of JSONPlaceholder's /todos, with the exact shape of the JSON. It's a DTO (data transfer object): a type that only describes an exchange format and has no behavior.
  • TaskItem is what the user owns: the task stored in SwiftData, whether it was written in the app or imported.

Why Two Types and Not One

It would be shorter for the @Model to be Decodable and get stored just as it arrives. The cost is that a sample API's format would be stitched to your database schema: if the API renames a field, your store changes; if you want to store something the API doesn't have, like a due date, the type no longer describes the JSON. Besides, @Model rewrites the class's properties, and a @Model that adopts Codable forces you to write the decoding by hand.

With two types, each one changes for its own reason, and going from one to the other is a small function you test without a network and without a database. Create the NativeTaskManager/Models/ folder and, inside it, the two files.

The Model

NativeTaskManager/Models/TaskItem.swift
import Foundation
import SwiftData
 
/// A task the user owns. It lives in the local SwiftData store, whether it was typed in the app or
/// imported from the sample API.
@Model
final class TaskItem {
    @Attribute(.unique) var id: UUID
    var title: String
    var notes: String
    var isCompleted: Bool
    var dueDate: Date?
    var createdAt: Date
    /// The sample API id when the task was imported; nil when it was created in the app.
    /// Unique, so the same sample can never be stored twice. SQLite treats NULLs as distinct,
    /// so any number of local tasks (remoteID == nil) can coexist.
    @Attribute(.unique) var remoteID: Int?
 
    init(
        id: UUID = UUID(),
        title: String,
        notes: String = "",
        isCompleted: Bool = false,
        dueDate: Date? = nil,
        createdAt: Date = .now,
        remoteID: Int? = nil
    ) {
        self.id = id
        self.title = title
        self.notes = notes
        self.isCompleted = isCompleted
        self.dueDate = dueDate
        self.createdAt = createdAt
        self.remoteID = remoteID
    }
}

It's a @Model like the one in "SwiftData and Core Data", with two uniqueness constraints:

  • id is the app's own unique UUID: the task's identity inside the app.
  • remoteID is the identifier the task had in the API, or nil if you created it in the app. It's also unique, so the same sample can't be stored twice. Being optional doesn't get in the way: a test in step 06 checks that many tasks with remoteID == nil coexist.

@Attribute(.unique) declares the constraint on a single property. The #Unique macro does the same for combinations of properties, for example remoteID together with a user identifier if the app imported from several accounts.

TaskItem stays on the main actor, because of the target setting. That's correct: the model is used with SwiftData's main context from the interface, and that context can't be shared across threads.

The DTO

NativeTaskManager/Models/RemoteTodo.swift
import Foundation
 
/// One item of JSONPlaceholder's `/todos`: `{"userId": 1, "id": 1, "title": "...", "completed": false}`.
///
/// A plain value that only describes the wire format. It is `nonisolated` because the app target
/// isolates everything to the main actor by default, and a DTO has to be decodable anywhere.
nonisolated struct RemoteTodo: Decodable, Sendable, Equatable {
    let userId: Int
    let id: Int
    let title: String
    let completed: Bool
}
 
extension TaskItem {
    /// Builds a local task from a sample todo. From here on the task belongs to the app:
    /// the sample API never sees the edits.
    convenience init(remote: RemoteTodo, importedAt: Date = .now) {
        let title = remote.title.trimmingCharacters(in: .whitespacesAndNewlines)
        self.init(
            title: title.isEmpty ? "Untitled task" : title,
            isCompleted: remote.completed,
            createdAt: importedAt,
            remoteID: remote.id
        )
    }
}

The struct has the JSON's four fields with their exact names, so Decodable is synthesized on its own, as in "URLSession and Codable". What's new is nonisolated in front of the struct.

A DTO has to be decodable in any context, also outside the main actor, and nonisolated takes it out of the target's default isolation.

Going deeper

what happens without nonisolated. With Approachable Concurrency, the Decodable conformance of a main-actor type is also isolated to the main actor. I compiled the same struct without that word, with the same settings as the app, decoding it inside a @concurrent function. The compiler gave:

error: main actor-isolated conformance of 'RemoteTodo' to 'Decodable' cannot be used in @concurrent context [#IsolatedConformances]

The mapping, in the extension in the same file, is a convenience initializer of TaskItem: it trims the spaces from the title, replaces an empty title with "Untitled task", and stores the API's id in remoteID. The task's own id is a different, new one.

Going deeper

a SwiftData unique attribute doesn't behave like an SQL constraint that rejects the second insert. A test in step 06 inserts two TaskItem with the same remoteID and saves: one row remains, with the values of the second. It's a silent upsert (update if it exists, insert if it doesn't). If the import relied on that, reimporting would overwrite what the user edited; that's why the import in step 07 looks before it inserts.

Going deeper

the tests for this step. Create RemoteTodoMappingTests.swift in the NativeTaskManagerTests/ folder and, after that, delete the template's empty test, NativeTaskManagerTests/NativeTaskManagerTests.swift (right-click › Delete › Move to Trash).

NativeTaskManagerTests/RemoteTodoMappingTests.swift
import Foundation
import Testing
@testable import NativeTaskManager
 
struct RemoteTodoMappingTests {
    @Test func decodesTheJSONPlaceholderShape() throws {
        let json = Data("""
        [{"userId": 1, "id": 4, "title": "et porro tempora", "completed": true}]
        """.utf8)
 
        let todos = try JSONDecoder().decode([RemoteTodo].self, from: json)
 
        #expect(todos == [RemoteTodo(userId: 1, id: 4, title: "et porro tempora", completed: true)])
    }
 
    @Test func ignoresFieldsTheAppDoesNotUse() throws {
        let json = Data(#"{"userId": 1, "id": 2, "title": "x", "completed": false, "extra": [1, 2]}"#.utf8)
 
        let todo = try JSONDecoder().decode(RemoteTodo.self, from: json)
 
        #expect(todo.id == 2)
    }
 
    @Test func failsWhenARequiredFieldIsMissing() {
        let json = Data(#"{"userId": 1, "id": 2, "title": "x"}"#.utf8)
 
        #expect(throws: DecodingError.self) {
            try JSONDecoder().decode(RemoteTodo.self, from: json)
        }
    }
 
    @MainActor
    @Test func mapsATodoToALocalTask() {
        let importedAt = Date(timeIntervalSince1970: 1_700_000_000)
        let todo = RemoteTodo(userId: 1, id: 7, title: "illo expedita", completed: true)
 
        let task = TaskItem(remote: todo, importedAt: importedAt)
 
        #expect(task.title == "illo expedita")
        #expect(task.isCompleted)
        #expect(task.remoteID == 7)
        #expect(task.notes.isEmpty)
        #expect(task.dueDate == nil)
        #expect(task.createdAt == importedAt)
    }
 
    @MainActor
    @Test(arguments: [("  padded title \n", "padded title"), ("   ", "Untitled task")])
    func normalizesTheTitle(raw: String, expected: String) {
        let task = TaskItem(remote: RemoteTodo(userId: 1, id: 1, title: raw, completed: false))
 
        #expect(task.title == expected)
    }
 
    @MainActor
    @Test func eachMappedTaskGetsItsOwnLocalID() {
        let todo = RemoteTodo(userId: 1, id: 1, title: "a", completed: false)
 
        #expect(TaskItem(remote: todo).id != TaskItem(remote: todo).id)
    }
}

These are the tools from "Tests: Swift Testing, XCTest, and Test Doubles": @Test, #expect, and a test with arguments that runs once per input-output pair. The ones that create a TaskItem carry @MainActor, because the model's initializer belongs to the main actor and the test target doesn't by default. The decoding ones don't need it.

Try it yourself: the screen doesn't change, because this step has no new interface. ⌘U has to count 8 tests: the 6 new ones and the template's 2 UI tests.

The usual mistake: with synchronized folders, deleting a folder's only file from the terminal can delete the folder. It happened to me when I replaced the template's test with git rm: it took NativeTaskManagerTests/ with it, and creating the new file failed with no such file or directory. That's the reason for the order above: first the new file, then the deletion.

Check what you learned. What would you lose if TaskItem were Decodable and you stored directly what arrives from the API?

Solution

Your database schema would be tied to a format you don't control: a change in the JSON would force you to migrate the store, and the app's own fields (notes, due date) wouldn't fit in a type that describes the JSON. Besides, you'd have to write the decoding by hand, because @Model rewrites the properties.

What to take away: what arrives from the network and what you store are different types, joined by a mapping you test without a network or a database.

Download the code for step 02.

Step 03: The First Screen

What does the user see when there's nothing yet? The template's ContentView goes out and the app's screen comes in: a navigation stack with the title "Tasks" that shows the tasks it receives, or an empty state if there are none.

The Screen

Create the NativeTaskManager/Features/TaskList/ folder and, inside it, the file:

NativeTaskManager/Features/TaskList/TaskListView.swift
import SwiftUI
 
/// The main screen. For now it only shows the tasks it is given; the store arrives in step 04.
struct TaskListView: View {
    var tasks: [TaskItem] = []
 
    var body: some View {
        NavigationStack {
            Group {
                if tasks.isEmpty {
                    ContentUnavailableView(
                        "No Tasks",
                        systemImage: "checklist",
                        description: Text("Tasks you add will appear here.")
                    )
                } else {
                    List(tasks) { task in
                        Text(task.title)
                    }
                }
            }
            .navigationTitle("Tasks")
        }
    }
}
 
#Preview("With tasks") {
    TaskListView(tasks: TaskItem.samples())
}
 
#Preview("Empty") {
    TaskListView()
}
  • NavigationStack is the navigation stack from "Navigation With NavigationStack". It doesn't navigate anywhere yet: it provides the bar with the title.
  • ContentUnavailableView is SwiftUI's view for "there's nothing to show": an icon, a title, and a description, centered. It tells the user what's going on and what they can do.
  • The view receives the tasks as a parameter. There's no database or view model yet, and this way you can see it with data in Xcode's preview without setting up anything else.

The files are grouped by feature (the list, later the form) and not by technical layer (all the views together, all the view models together): that way, the files that change together stay together.

The Sample Tasks for the Previews

NativeTaskManager/Models/TaskItem+Samples.swift
import Foundation
 
extension TaskItem {
    /// A fixed set of tasks for SwiftUI previews. Built fresh on every call, so a preview that
    /// mutates one task never leaks the change into another preview.
    static func samples(now: Date = .now) -> [TaskItem] {
        let day: TimeInterval = 24 * 60 * 60
        return [
            TaskItem(title: "Review the pull request", notes: "Check the migration first.", dueDate: now.addingTimeInterval(day)),
            TaskItem(title: "Book the dentist", isCompleted: true),
            TaskItem(title: "Write the release notes", dueDate: now.addingTimeInterval(3 * day)),
        ]
    }
}

samples is a function and not a static let constant. TaskItem is a class, and a constant would share the same instances across all the previews: if one marked a task as completed, the other would see it that way. The function creates new objects on every call.

A @Model can be created without inserting it into any context, like any other object. The tests in step 02 already did it: they create a TaskItem without a container and check its fields.

The App Shows the List

NativeTaskManager/NativeTaskManagerApp.swift
--- a/NativeTaskManager/NativeTaskManagerApp.swift
+++ b/NativeTaskManager/NativeTaskManagerApp.swift
@@ -4,7 +4,7 @@
 struct NativeTaskManagerApp: App {
     var body: some Scene {
         WindowGroup {
-            ContentView()
+            TaskListView()
         }
     }
 }

And you delete ContentView.swift: right-click the file › Delete › Move to Trash.

Try it yourself: ⌘R. The screen shows "Tasks" at the top and, in the middle, "No Tasks": there's nowhere to read tasks from yet. To see the list with data, open TaskListView.swift and show the canvas (Editor › Canvas, or ⌥⌘↩): the "With tasks" preview draws the three sample tasks. ⌘U is still at 8 tests.

The app in the simulator with the title Tasks and, in the middle, the empty state: a list icon, the text No Tasks, and the description Tasks you add will appear here.
The first screen, still without data.

Check what you learned. Why does the view receive [TaskItem] as a parameter instead of reading them from somewhere?

Solution

Because there's no store yet, and this way the screen can be built and seen in the preview with sample data. A view that receives what it shows doesn't depend on where the data comes from; step 06 builds on that idea to give it a view model.

What to take away: an empty screen is still a screen: tell the user what's going on and what they can do.

Download the code for step 03.

Step 04: The List on SwiftData

Where do the tasks live when you close the app? In a SwiftData store on disk. The list reads it, and each row can mark its task as completed.

The Store

NativeTaskManager/NativeTaskManagerApp.swift
--- a/NativeTaskManager/NativeTaskManagerApp.swift
+++ b/NativeTaskManager/NativeTaskManagerApp.swift
@@ -1,3 +1,4 @@
+import SwiftData
 import SwiftUI
 
 @main
@@ -6,5 +7,7 @@
         WindowGroup {
             TaskListView()
         }
+        // One on-disk store for the whole app; every view below reads it from the environment.
+        .modelContainer(for: TaskItem.self)
     }
 }

The .modelContainer(for:) modifier on the scene creates a ModelContainer for TaskItem, only once, stored in the app's container on the device, and puts it in SwiftUI's environment: the set of values a view passes to every view it contains, the same one as @Environment in part 2. That container's main context has autosave turned on.

The List Reads With @Query

NativeTaskManager/Features/TaskList/TaskListView.swift
--- a/NativeTaskManager/Features/TaskList/TaskListView.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListView.swift
@@ -1,8 +1,10 @@
+import SwiftData
 import SwiftUI
 
-/// The main screen. For now it only shows the tasks it is given; the store arrives in step 04.
+/// The main screen. In this step the view reads the store directly with `@Query`; step 06 moves
+/// fetching and mutations into a view model.
 struct TaskListView: View {
-    var tasks: [TaskItem] = []
+    @Query(sort: \TaskItem.createdAt, order: .reverse) private var tasks: [TaskItem]
 
     var body: some View {
         NavigationStack {
@@ -15,7 +17,8 @@
                     )
                 } else {
                     List(tasks) { task in
-                        Text(task.title)
+                        // The model is a reference type: toggling it here is saved by SwiftData's autosave.
+                        TaskRowView(task: task, onToggle: { task.isCompleted.toggle() })
                     }
                 }
             }
@@ -25,9 +28,11 @@
 }
 
 #Preview("With tasks") {
-    TaskListView(tasks: TaskItem.samples())
+    TaskListView()
+        .modelContainer(.preview(with: TaskItem.samples()))
 }
 
 #Preview("Empty") {
     TaskListView()
+        .modelContainer(.preview(with: []))
 }

@Query is the shortest way to show SwiftData data in a view: it declares a query (here, every task, from newest to oldest), reads the container from the environment, and redraws the view when the data changes.

It's a decision with an expiration date, and I'm telling you now. With @Query, the view owns the query and changes the model directly (task.isCompleted.toggle(), saved by autosave), and that can only be tested by standing up the view. While the screen only shows data, that's enough. In step 06, when the import, the states, and the filters arrive, all of it moves to a view model you test without an interface.

The Row

NativeTaskManager/Features/TaskList/TaskRowView.swift
import SwiftUI
 
/// One task in the list: a completion button, the title and the due date.
struct TaskRowView: View {
    let task: TaskItem
    let onToggle: () -> Void
 
    var body: some View {
        HStack(alignment: .firstTextBaseline, spacing: 12) {
            Button(action: onToggle) {
                // Shape, not only color, tells completed from pending.
                Image(systemName: task.isCompleted ? "checkmark.circle.fill" : "circle")
                    .imageScale(.large)
                    .frame(minWidth: 44, minHeight: 44)
                    .contentShape(Rectangle())
            }
            .buttonStyle(.borderless)
            .accessibilityLabel(task.isCompleted ? "Mark as not completed" : "Mark as completed")
 
            VStack(alignment: .leading, spacing: 4) {
                Text(task.title)
                    .strikethrough(task.isCompleted)
                    .foregroundStyle(task.isCompleted ? .secondary : .primary)
                if let dueDate = task.dueDate {
                    Text("Due \(dueDate, format: .dateTime.day().month().year())")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
            }
        }
        .accessibilityElement(children: .combine)
        .accessibilityValue(task.isCompleted ? "Completed" : "Not completed")
    }
}
 
#Preview {
    List(TaskItem.samples()) { task in
        TaskRowView(task: task, onToggle: { task.isCompleted.toggle() })
    }
}

The row has a button to complete the task and, next to it, the title and the date. The accessibility details are worth adding from the first version:

  • Shape, not just color. Completed or pending is told apart by the icon (circle or checkmark.circle.fill) and by the struck-through title.
  • A name for VoiceOver, the iOS screen reader, which says out loud what's under your finger. The button only has an icon, so accessibilityLabel gives it a name that says the action: "Mark as completed" or "Mark as not completed".
  • A 44 × 44 point touch area. frame(minWidth:minHeight:) enlarges the button and contentShape makes that whole area respond to a tap.
  • .buttonStyle(.borderless). Inside a List, a button with the default style takes the tap for the whole row. With .borderless only the button responds, and the row stays free for editing in step 10.

The Previews

NativeTaskManager/Models/ModelContainer+Preview.swift
import SwiftData
 
extension ModelContainer {
    /// An in-memory store filled with the given tasks, for previews. Nothing touches the disk.
    static func preview(with tasks: [TaskItem]) -> ModelContainer {
        do {
            let container = try ModelContainer(
                for: TaskItem.self,
                configurations: ModelConfiguration(isStoredInMemoryOnly: true)
            )
            for task in tasks {
                container.mainContext.insert(task)
            }
            return container
        } catch {
            fatalError("Could not create the preview store: \(error)")
        }
    }
}

A view with @Query needs a container in the environment, in the preview too. This extension creates one in memory (isStoredInMemoryOnly: true), which writes nothing to disk, and fills it with the tasks it receives. It lives until step 06.

Try it yourself: ⌘R. The app still shows "No Tasks": the store is empty and there's no way to add tasks yet. You can see the list in the canvas, in the "With tasks" preview: tap a task's circle and it gets struck through. ⌘U is still at 8 tests; the template's UI test launches the app, so it already checks that the SwiftData container is created without failing.

Check what you learned. In this step, who saves the change when you tap a task's circle?

Solution

The main context's autosave. The view changes isCompleted on the object, which is a class, and the main context of a container created with .modelContainer(for:) has autosave turned on. Nobody calls save(); from step 06 on, the repository does.

What to take away: @Query is the shortest way to show stored data; when the screen needs logic you want to test, that logic moves out of the view.

Download the code for step 04.

Note: a good point for a break: you've done 4 of the 12 steps, roughly an hour and a half. What follows is the part that gets tested the most: validating, separating the state, and talking to the network.

Step 05: The Form and Its Validation

What happens if someone saves a task without a title? Nothing, if the form doesn't allow it. The "+" button opens a sheet to create a task, and before the view comes the rule: what a valid task is, written as a function that knows nothing about SwiftUI or SwiftData.

The Rules

  • The title, without the spaces at its ends, can't be empty or longer than 80 characters.
  • The due date is optional. When you create a task it can't be earlier than today; when you edit it, it can: an overdue task is still a task.
  • "Today" is compared by day, not by instant: a task due today at 8:00 is valid at 17:00.

The Validator

Create the NativeTaskManager/Features/TaskForm/ folder. The first file holds the three validation types:

NativeTaskManager/Features/TaskForm/TaskValidator.swift
import Foundation
 
/// What the form edits: plain values, no SwiftData, so validation is a pure function.
nonisolated struct TaskDraft: Equatable, Sendable {
    var title = ""
    var notes = ""
    var dueDate: Date?
 
    /// The draft as it will be stored: title and notes without surrounding whitespace.
    var normalized: TaskDraft {
        TaskDraft(
            title: title.trimmingCharacters(in: .whitespacesAndNewlines),
            notes: notes.trimmingCharacters(in: .whitespacesAndNewlines),
            dueDate: dueDate
        )
    }
}
 
nonisolated struct TaskValidation: Equatable, Sendable {
    enum TitleError: Equatable, Sendable {
        case empty
        case tooLong(count: Int)
    }
 
    enum DueDateError: Equatable, Sendable {
        case beforeToday
    }
 
    var title: TitleError?
    var dueDate: DueDateError?
 
    var isValid: Bool { title == nil && dueDate == nil }
}
 
nonisolated struct TaskValidator: Sendable {
    static let maxTitleLength = 80
 
    var calendar: Calendar = .current
 
    /// `now` is a parameter, not `Date()`, so tests decide what "today" is.
    func validate(_ draft: TaskDraft, isCreating: Bool, now: Date) -> TaskValidation {
        var result = TaskValidation()
 
        // Characters, not UTF-16 units: "👩‍💻" counts as one.
        let title = draft.title.trimmingCharacters(in: .whitespacesAndNewlines)
        if title.isEmpty {
            result.title = .empty
        } else if title.count > Self.maxTitleLength {
            result.title = .tooLong(count: title.count)
        }
 
        // Compare days, not instants: a task due "today" at 08:00 is fine at 17:00.
        // An existing task may keep a past date (it is simply overdue).
        if isCreating, let dueDate = draft.dueDate,
           calendar.startOfDay(for: dueDate) < calendar.startOfDay(for: now) {
            result.dueDate = .beforeToday
        }
        return result
    }
}
 
extension TaskValidation.TitleError {
    var message: String {
        switch self {
        case .empty: "Enter a title."
        case .tooLong(let count): "Use at most \(TaskValidator.maxTitleLength) characters (now \(count))."
        }
    }
}
 
extension TaskValidation.DueDateError {
    var message: String {
        switch self {
        case .beforeToday: "Choose today or a later date."
        }
    }
}

All three are nonisolated (off the main actor) and Sendable, because they don't touch the interface:

  • TaskDraft is what the form edits: loose values, without SwiftData. normalized returns the draft as it will be stored, without spaces at the ends.
  • TaskValidation is the result: an optional error per field, with associated values when needed (tooLong(count:) carries how many characters there are). It's the pattern from "Enumerations".
  • TaskValidator decides. It receives now and a Calendar as parameters instead of reading the time inside: that way a test sets which day "today" is and in which time zone.

title.count counts characters the way a person sees them, not code units: an emoji with a skin tone is one character, even though it takes four UTF-16 units.

The Bridge to the Model

NativeTaskManager/Features/TaskForm/TaskDraft+TaskItem.swift
import Foundation
 
// This extension is on the main actor (the target default), like TaskItem itself.
extension TaskDraft {
    init(task: TaskItem) {
        self.init(title: task.title, notes: task.notes, dueDate: task.dueDate)
    }
 
    func makeTask() -> TaskItem {
        let draft = normalized
        return TaskItem(title: draft.title, notes: draft.notes, dueDate: draft.dueDate)
    }
 
    func apply(to task: TaskItem) {
        let draft = normalized
        task.title = draft.title
        task.notes = draft.notes
        task.dueDate = draft.dueDate
    }
}

TaskDraft is nonisolated, but this extension doesn't say so, so it stays on the main actor because of the target setting. That's correct: it reads and writes a TaskItem, which belongs to the main actor.

Why edit a draft and not the @Model directly? Because with the model, every key the user typed would change the stored object, autosave would persist it, and Cancel couldn't undo anything. With a draft, the model only changes when you tap Save.

The Sheet

NativeTaskManager/Features/TaskForm/TaskFormView.swift
import SwiftUI
 
/// Create or edit a task in a sheet. The form only edits a `TaskDraft`; the caller decides what
/// saving means.
struct TaskFormView: View {
    let isCreating: Bool
    let onSave: (TaskDraft) -> Void
 
    @Environment(\.dismiss) private var dismiss
    @State private var draft: TaskDraft
    @State private var titleEdited = false
 
    private let validator = TaskValidator()
 
    init(draft: TaskDraft = TaskDraft(), isCreating: Bool, onSave: @escaping (TaskDraft) -> Void) {
        self.isCreating = isCreating
        self.onSave = onSave
        _draft = State(initialValue: draft)
    }
 
    private var validation: TaskValidation {
        validator.validate(draft, isCreating: isCreating, now: .now)
    }
 
    var body: some View {
        NavigationStack {
            Form {
                Section {
                    TextField("Title", text: $draft.title)
                        .onChange(of: draft.title) { titleEdited = true }
                    // Shown once the user has typed, so an empty new form is not red from the start.
                    if titleEdited, let error = validation.title {
                        FieldError(message: error.message)
                    }
                }
 
                Section {
                    TextField("Notes", text: $draft.notes, axis: .vertical)
                        .lineLimit(3...8)
                }
 
                Section {
                    Toggle("Due date", isOn: hasDueDate)
                    if draft.dueDate != nil {
                        DatePicker("Due", selection: dueDate, displayedComponents: .date)
                        if let error = validation.dueDate {
                            FieldError(message: error.message)
                        }
                    }
                }
            }
            .navigationTitle(isCreating ? "New Task" : "Edit Task")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Save") {
                        onSave(draft.normalized)
                        dismiss()
                    }
                    .disabled(!validation.isValid)
                }
            }
        }
    }
 
    private var hasDueDate: Binding<Bool> {
        Binding(
            get: { draft.dueDate != nil },
            set: { draft.dueDate = $0 ? Calendar.current.startOfDay(for: .now) : nil }
        )
    }
 
    private var dueDate: Binding<Date> {
        Binding(get: { draft.dueDate ?? .now }, set: { draft.dueDate = $0 })
    }
}
 
/// An inline validation message: an icon and text, so it does not rely on red alone.
private struct FieldError: View {
    let message: String
 
    var body: some View {
        Label(message, systemImage: "exclamationmark.circle")
            .font(.footnote)
            .foregroundStyle(.red)
    }
}
 
#Preview("New") {
    TaskFormView(isCreating: true, onSave: { _ in })
}
 
#Preview("Edit") {
    TaskFormView(draft: TaskDraft(title: "Review the pull request"), isCreating: false, onSave: { _ in })
}

It's a Form like the ones in "Lists and Forms", with these decisions:

  • The title error appears after typing. titleEdited becomes true on the field's first change (onChange(of:)). Without that, the sheet would open already in red.
  • Save stays disabled while the validation doesn't pass. Cancel and Save go in the places the system reserves for them (.cancellationAction and .confirmationAction).
  • The error carries an icon as well as a color. Red alone doesn't help someone who can't tell it apart.
  • The due date is a toggle plus a picker. The Toggle is bound to a computed Binding: turning it on sets today's date, turning it off makes it nil. The DatePicker doesn't limit the range (in:): the rule lives in the validator, and a sheet opened past midnight still follows it.
  • dismiss comes from the environment (@Environment(\.dismiss)) and closes the sheet.

The sheet doesn't know what saving means: it receives onSave and passes it the draft. Whoever opens it decides.

The List Opens the Sheet

NativeTaskManager/Features/TaskList/TaskListView.swift
--- a/NativeTaskManager/Features/TaskList/TaskListView.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListView.swift
@@ -5,6 +5,8 @@
 /// fetching and mutations into a view model.
 struct TaskListView: View {
     @Query(sort: \TaskItem.createdAt, order: .reverse) private var tasks: [TaskItem]
+    @Environment(\.modelContext) private var modelContext
+    @State private var isCreating = false
 
     var body: some View {
         NavigationStack {
@@ -13,7 +15,7 @@
                     ContentUnavailableView(
                         "No Tasks",
                         systemImage: "checklist",
-                        description: Text("Tasks you add will appear here.")
+                        description: Text("Tap + to add your first task.")
                     )
                 } else {
                     List(tasks) { task in
@@ -23,6 +25,16 @@
                 }
             }
             .navigationTitle("Tasks")
+            .toolbar {
+                ToolbarItem(placement: .primaryAction) {
+                    Button("Add Task", systemImage: "plus") { isCreating = true }
+                }
+            }
+            .sheet(isPresented: $isCreating) {
+                TaskFormView(isCreating: true) { draft in
+                    modelContext.insert(draft.makeTask())
+                }
+            }
         }
     }
 }

The "+" button goes in the bar with ToolbarItem(placement: .primaryAction). Its text, "Add Task", isn't shown (the icon is), but it's the name VoiceOver reads and the one the UI test in step 11 uses. On save, the view inserts the task into the environment's modelContext; autosave persists it.

Going deeper

the tests for this step. Create TaskValidatorTests.swift in NativeTaskManagerTests/.

NativeTaskManagerTests/TaskValidatorTests.swift
import Foundation
import Testing
@testable import NativeTaskManager
 
struct TaskValidatorTests {
    // A fixed "now" and calendar: the result never depends on when or where the test runs.
    private static let utc: Calendar = {
        var calendar = Calendar(identifier: .gregorian)
        calendar.timeZone = TimeZone(identifier: "UTC")!
        return calendar
    }()
 
    private let validator = TaskValidator(calendar: utc)
    private let now = Date(timeIntervalSince1970: 1_795_180_000) // 2026-11-20 13:06 UTC
 
    private func date(_ year: Int, _ month: Int, _ day: Int, hour: Int = 0) -> Date {
        Self.utc.date(from: DateComponents(year: year, month: month, day: day, hour: hour))!
    }
 
    @Test func acceptsATitleWithoutDueDate() {
        let result = validator.validate(TaskDraft(title: "Buy milk"), isCreating: true, now: now)
 
        #expect(result.isValid)
    }
 
    @Test(arguments: ["", "   ", "\n\t "])
    func rejectsABlankTitle(title: String) {
        let result = validator.validate(TaskDraft(title: title), isCreating: true, now: now)
 
        #expect(result.title == .empty)
        #expect(!result.isValid)
    }
 
    @Test func acceptsExactlyTheMaximumLength() {
        let title = String(repeating: "a", count: TaskValidator.maxTitleLength)
 
        #expect(validator.validate(TaskDraft(title: title), isCreating: true, now: now).title == nil)
    }
 
    @Test func rejectsOneCharacterOverTheMaximum() {
        let title = String(repeating: "a", count: TaskValidator.maxTitleLength + 1)
 
        let result = validator.validate(TaskDraft(title: title), isCreating: true, now: now)
 
        #expect(result.title == .tooLong(count: 81))
    }
 
    @Test func measuresTheTrimmedTitle() {
        let title = "  " + String(repeating: "a", count: TaskValidator.maxTitleLength) + "  "
 
        #expect(validator.validate(TaskDraft(title: title), isCreating: true, now: now).title == nil)
    }
 
    @Test func countsCharactersNotCodeUnits() {
        // 80 emoji with skin tone are 80 Characters but 320 UTF-16 code units.
        let title = String(repeating: "👍🏽", count: TaskValidator.maxTitleLength)
 
        #expect(title.utf16.count == 320)
        #expect(validator.validate(TaskDraft(title: title), isCreating: true, now: now).title == nil)
    }
 
    @Test func rejectsADueDateBeforeTodayWhenCreating() {
        let draft = TaskDraft(title: "Late", dueDate: date(2026, 11, 19, hour: 23))
 
        #expect(validator.validate(draft, isCreating: true, now: now).dueDate == .beforeToday)
    }
 
    @Test func acceptsEarlierTodayWhenCreating() {
        let draft = TaskDraft(title: "Today", dueDate: date(2026, 11, 20, hour: 0))
 
        #expect(validator.validate(draft, isCreating: true, now: now).isValid)
    }
 
    @Test func acceptsAPastDueDateWhenEditing() {
        let draft = TaskDraft(title: "Overdue", dueDate: date(2026, 1, 1))
 
        #expect(validator.validate(draft, isCreating: false, now: now).isValid)
    }
 
    @Test func reportsBothErrorsAtOnce() {
        let draft = TaskDraft(title: " ", dueDate: date(2025, 1, 1))
 
        let result = validator.validate(draft, isCreating: true, now: now)
 
        #expect(result == TaskValidation(title: .empty, dueDate: .beforeToday))
    }
 
    @Test func normalizedTrimsTitleAndNotes() {
        let draft = TaskDraft(title: "  Call Ana ", notes: "\nafter 5 pm  ")
 
        #expect(draft.normalized == TaskDraft(title: "Call Ana", notes: "after 5 pm"))
    }
 
    @MainActor
    @Test func makeTaskStoresTheNormalizedDraft() {
        let task = TaskDraft(title: " Pay rent ", notes: " ").makeTask()
 
        #expect(task.title == "Pay rent")
        #expect(task.notes.isEmpty)
        #expect(!task.isCompleted)
        #expect(task.remoteID == nil)
    }
}

Twelve tests that cover the edges: 80 characters pass, 81 don't; the spaces at the ends don't count; 80 emoji with a skin tone are 80 characters; yesterday at 23:00 is "before today" when creating, today at 0:00 isn't; a past date is valid when editing. "Now" is a fixed instant and the calendar is in UTC, so the result is the same on any Mac and at any hour. Only makeTaskStoresTheNormalizedDraft carries @MainActor: it's the only one that creates a TaskItem.

Try it yourself: ⌘R and tap "+". The sheet opens with Save disabled. Type a letter and delete it: "Enter a title." appears under the field, with its icon. Type a title, turn on "Due date", and save: the task appears in the list. Wait a second, stop the app from Xcode (⌘.), and launch it again: the task is still there, because the store is on disk (in this step autosave saves it, hence the one-second wait). ⌘U has to count 20 tests.

The New Task sheet in the simulator: the empty Title field with the message Enter a title. and its exclamation icon below it, the Due date toggle, and the Save button disabled at the top right.
The form doesn't let you save an empty title, and it says why under the field.

The usual mistake: writing the date test with Date() inside the validator. The "today at 0:00 is valid" test passes during the day and fails at night, or the other way around depending on your time zone. If a rule depends on the clock, the clock is a parameter.

Check what you learned. Why does the form edit a TaskDraft and not the TaskItem?

Solution

Because the model is a class saved with autosave: every change in the form would be persisted even if the user tapped Cancel. With a draft of values, the model only changes on save, and the validation is a pure function you test without SwiftData.

What to take away: a business rule is a pure function that receives everything it uses, the time included; the view only shows it.

Download the code for step 05.

Step 06: The View Model and the Repository

How do you test a screen without opening it? By taking its logic out of the view. Until now the view read the store, changed the model, and inserted tasks. What comes next (importing, loading states, errors, filters) is logic you want to test without standing up a screen, so this step moves it to a view model, as in "Architecture: MVC, MVVM, and Clean Without Overengineering".

The Repository

A repository is the object that knows how to save and read, and offers the rest of the app only the operations it needs. Create the NativeTaskManager/Data/ folder and, inside it:

NativeTaskManager/Data/TaskRepository.swift
import Foundation
import SwiftData
 
/// What the view model needs from storage. A protocol so tests can swap in a failing fake; the
/// app has a single implementation over SwiftData.
protocol TaskRepository {
    func fetchAll() throws -> [TaskItem]
    func add(_ task: TaskItem) throws
    func delete(_ task: TaskItem) throws
    /// Persists changes made to tasks that are already stored (toggle, edit).
    func save() throws
}
 
final class SwiftDataTaskRepository: TaskRepository {
    // The container is kept on purpose: a ModelContext does not keep its container alive, and
    // using the context after the container is gone crashes.
    private let container: ModelContainer
    private var context: ModelContext { container.mainContext }
 
    init(container: ModelContainer) {
        self.container = container
    }
 
    func fetchAll() throws -> [TaskItem] {
        try context.fetch(FetchDescriptor<TaskItem>(sortBy: [SortDescriptor(\.createdAt, order: .reverse)]))
    }
 
    func add(_ task: TaskItem) throws {
        context.insert(task)
        try context.save()
    }
 
    func delete(_ task: TaskItem) throws {
        context.delete(task)
        try context.save()
    }
 
    func save() throws {
        try context.save()
    }
}

TaskRepository is a four-method protocol, and SwiftDataTaskRepository is its only implementation. The protocol isn't there to switch databases someday: it's there so a test can put a repository that fails on purpose in its place. For everything else, the tests use real SwiftData, in memory, which tests more than a fake object.

Each write calls save() even though the main context has autosave. That way an error shows up where it happened, and the tests don't depend on when the automatic save runs.

This version has a gap, and I'm telling you before you find it: if save() fails, the change stays pending in the context, and the list would show it as done while the alert says it wasn't saved. Step 12 closes it by undoing the change.

The View Model

NativeTaskManager/Features/TaskList/TaskListViewModel.swift
import Foundation
import Observation
 
/// Owns the task list: what is loaded, what is visible and every change the user makes.
/// On the main actor (the target default), like the SwiftData context it uses.
@Observable
final class TaskListViewModel {
    enum LoadState: Equatable {
        case idle
        case loading
        case loaded
        case empty
        case failed(message: String)
    }
 
    enum Filter: String, CaseIterable, Identifiable {
        case all, active, completed
 
        var id: Self { self }
 
        func includes(_ task: TaskItem) -> Bool {
            switch self {
            case .all: true
            case .active: !task.isCompleted
            case .completed: task.isCompleted
            }
        }
    }
 
    private(set) var state: LoadState = .idle
    private(set) var tasks: [TaskItem] = []
    var filter: Filter = .all
    /// A failed change (save, delete). The list stays on screen; the view shows an alert.
    var errorMessage: String?
 
    var visibleTasks: [TaskItem] {
        tasks.filter(filter.includes)
    }
 
    private let repository: any TaskRepository
 
    init(repository: any TaskRepository) {
        self.repository = repository
    }
 
    func load() {
        do {
            tasks = try repository.fetchAll()
            state = tasks.isEmpty ? .empty : .loaded
        } catch {
            state = .failed(message: "Your tasks could not be read.")
        }
    }
 
    func add(_ draft: TaskDraft) {
        perform { try repository.add(draft.makeTask()) }
    }
 
    func update(_ task: TaskItem, with draft: TaskDraft) {
        draft.apply(to: task)
        perform { try repository.save() }
    }
 
    func toggleCompletion(of task: TaskItem) {
        task.isCompleted.toggle()
        perform { try repository.save() }
    }
 
    func delete(_ task: TaskItem) {
        perform { try repository.delete(task) }
    }
 
    /// Runs a change, then re-reads the store so `tasks` always mirrors what is persisted.
    private func perform(_ change: () throws -> Void) {
        do {
            try change()
        } catch {
            errorMessage = "The change could not be saved."
        }
        load()
    }
}

TaskListViewModel is @Observable, as in "State: Who Owns Each Piece of Data", and it's on the main actor because of the target setting, just like the SwiftData context it uses. It has:

  • LoadState, an enum with the screen's states: idle (it hasn't read anything yet), loading, loaded, empty, and failed(message:). The view does a switch on it, and the compiler forces you to cover every case. loading isn't used yet; the import will use it.
  • Filter, with all, active, and completed, and visibleTasks, the filtered list computed from tasks. It's computed, not stored: two stored lists would have to be kept in agreement.
  • The intents (load, add, update, toggleCompletion, delete): each user action is a method. The ones that write go through perform, which runs the change and reads the store again. With dozens of tasks, rereading costs nothing noticeable; with thousands, you'd update the array in place.
  • Two ways to fail. If the read fails, the whole screen goes to .failed. If a change fails, the list stays and errorMessage triggers an alert. The original error turns into text and is discarded, without logging it: another simplification that step 12 comes back to.

The Composition Root

Dependency injection is giving an object, from the outside, the pieces it uses, instead of having it create them. Here it's done through the initializer, TaskListViewModel(repository:). Someone has to create those pieces and connect them once, and that place is the composition root. Create the NativeTaskManager/App/ folder and, inside it:

NativeTaskManager/App/AppDependencies.swift
import Foundation
import SwiftData
 
/// The composition root: the one place that decides which concrete types the app uses.
/// Everything else receives its dependencies through initializers.
final class AppDependencies {
    let modelContainer: ModelContainer
    let repository: any TaskRepository
 
    init(modelContainer: ModelContainer) {
        self.modelContainer = modelContainer
        self.repository = SwiftDataTaskRepository(container: modelContainer)
    }
 
    /// The real app: an on-disk store in the app's container.
    static func live() -> AppDependencies {
        do {
            return AppDependencies(modelContainer: try ModelContainer(for: TaskItem.self))
        } catch {
            // Without its store the app cannot do anything useful; failing loudly beats a blank screen.
            fatalError("Could not open the task store: \(error)")
        }
    }
 
    /// Previews and tests: a store that lives only in memory, optionally pre-filled.
    static func inMemory(tasks: [TaskItem] = []) -> AppDependencies {
        do {
            let container = try ModelContainer(
                for: TaskItem.self,
                configurations: ModelConfiguration(isStoredInMemoryOnly: true)
            )
            tasks.forEach(container.mainContext.insert)
            try container.mainContext.save()
            return AppDependencies(modelContainer: container)
        } catch {
            fatalError("Could not create the in-memory store: \(error)")
        }
    }
 
    func makeTaskListViewModel() -> TaskListViewModel {
        TaskListViewModel(repository: repository)
    }
}
  • live() opens the store on disk. If it can't, the app stops with a message: without its store it can't do anything useful. It's a simplification; step 12 says what a published app would do.
  • inMemory(tasks:) creates an in-memory store, optionally with tasks. The previews and the tests use it, and it replaces the extension from step 04: delete NativeTaskManager/Models/ModelContainer+Preview.swift (right-click › Delete › Move to Trash).

There's no dependency container and no custom value in SwiftUI's environment: with one view model and one repository, an initializer is all the injection you need.

The App and the View

NativeTaskManager/NativeTaskManagerApp.swift
--- a/NativeTaskManager/NativeTaskManagerApp.swift
+++ b/NativeTaskManager/NativeTaskManagerApp.swift
@@ -1,13 +1,19 @@
-import SwiftData
 import SwiftUI
 
 @main
 struct NativeTaskManagerApp: App {
+    private let dependencies: AppDependencies
+    @State private var viewModel: TaskListViewModel
+
+    init() {
+        let dependencies = AppDependencies.live()
+        self.dependencies = dependencies
+        _viewModel = State(initialValue: dependencies.makeTaskListViewModel())
+    }
+
     var body: some Scene {
         WindowGroup {
-            TaskListView()
+            TaskListView(viewModel: viewModel)
         }
-        // One on-disk store for the whole app; every view below reads it from the environment.
-        .modelContainer(for: TaskItem.self)
     }
 }

The app creates the dependencies only once, in its init, and keeps the view model with @State: the app owns it, and @State keeps it alive as long as the app exists. There's no .modelContainer(...) anymore: no view reads the store from the environment.

A single view model for the whole app assumes a single window. On an iPhone that holds; on an iPad with several windows it doesn't, and step 12 says what would change.

NativeTaskManager/Features/TaskList/TaskListView.swift
import SwiftUI
 
/// The main screen. It renders the view model's state and forwards every user action to it.
struct TaskListView: View {
    @Bindable var viewModel: TaskListViewModel
    @State private var isCreating = false
 
    var body: some View {
        NavigationStack {
            content
                .navigationTitle("Tasks")
                .toolbar {
                    ToolbarItem(placement: .primaryAction) {
                        Button("Add Task", systemImage: "plus") { isCreating = true }
                    }
                }
                .sheet(isPresented: $isCreating) {
                    TaskFormView(isCreating: true) { draft in
                        viewModel.add(draft)
                    }
                }
                .alert(
                    "Something Went Wrong",
                    isPresented: Binding(
                        get: { viewModel.errorMessage != nil },
                        set: { if !$0 { viewModel.errorMessage = nil } }
                    ),
                    actions: { Button("OK") {} },
                    message: { Text(viewModel.errorMessage ?? "") }
                )
        }
        .task { viewModel.load() }
    }
 
    @ViewBuilder
    private var content: some View {
        switch viewModel.state {
        case .idle, .loading:
            ProgressView()
        case .empty:
            ContentUnavailableView(
                "No Tasks",
                systemImage: "checklist",
                description: Text("Tap + to add your first task.")
            )
        case .failed(let message):
            ContentUnavailableView(
                "Couldn't Load Tasks",
                systemImage: "exclamationmark.triangle",
                description: Text(message)
            )
        case .loaded:
            List(viewModel.visibleTasks) { task in
                TaskRowView(task: task, onToggle: { viewModel.toggleCompletion(of: task) })
            }
        }
    }
}
 
#Preview("With tasks") {
    TaskListView(viewModel: AppDependencies.inMemory(tasks: TaskItem.samples()).makeTaskListViewModel())
}
 
#Preview("Empty") {
    TaskListView(viewModel: AppDependencies.inMemory().makeTaskListViewModel())
}

The view receives the view model as @Bindable, which lets you create bindings to its properties (the filter in step 10 takes advantage of it). Its content is a switch on viewModel.state, and each user action calls a view model method. The initial read goes in .task, which runs when the view appears.

Why not stay with @Query? Because @Query lives in the view and reads from the environment: the view model can't use it, and the logic that's coming needs to be in the view model to be tested without an interface. @Query is still the shortest option when a screen only shows data.

Going deeper

the tests for this step. Two new files in NativeTaskManagerTests/. The first tests the repository against real SwiftData, in memory:

NativeTaskManagerTests/SwiftDataTaskRepositoryTests.swift
import Foundation
import SwiftData
import Testing
@testable import NativeTaskManager
 
/// Runs against a real SwiftData store that lives only in memory: a fresh one per test.
@MainActor
struct SwiftDataTaskRepositoryTests {
    private let dependencies = AppDependencies.inMemory()
    private var repository: any TaskRepository { dependencies.repository }
 
    @Test func fetchesNewestFirst() throws {
        try repository.add(TaskItem(title: "old", createdAt: Date(timeIntervalSince1970: 1)))
        try repository.add(TaskItem(title: "new", createdAt: Date(timeIntervalSince1970: 2)))
 
        #expect(try repository.fetchAll().map(\.title) == ["new", "old"])
    }
 
    @Test func manyLocalTasksCanHaveNoRemoteID() throws {
        try repository.add(TaskItem(title: "a"))
        try repository.add(TaskItem(title: "b"))
 
        #expect(try repository.fetchAll().count == 2)
    }
 
    @Test func aRepeatedRemoteIDReplacesTheStoredRow() throws {
        // SwiftData turns an insert that hits a unique attribute into an upsert. The import must
        // not rely on it: it would silently overwrite a task the user already edited.
        try repository.add(TaskItem(title: "edited by the user", remoteID: 1))
        try repository.add(TaskItem(title: "fresh from the API", remoteID: 1))
 
        let stored = try repository.fetchAll()
        #expect(stored.count == 1)
        #expect(stored.first?.title == "fresh from the API")
    }
 
    @Test func deleteRemovesTheTask() throws {
        let task = TaskItem(title: "temporary")
        try repository.add(task)
 
        try repository.delete(task)
 
        #expect(try repository.fetchAll().isEmpty)
    }
 
    @Test func savePersistsAChangeToAStoredTask() throws {
        let task = TaskItem(title: "toggle me")
        try repository.add(task)
 
        task.isCompleted = true
        try repository.save()
 
        // A second context reads straight from the store, not from the first context's memory.
        let other = ModelContext(dependencies.modelContainer)
        #expect(try other.fetch(FetchDescriptor<TaskItem>()).first?.isCompleted == true)
    }
}

Each test has its own store, so it doesn't matter in what order they run. Two of them measure what step 02 claimed: manyLocalTasksCanHaveNoRemoteID (two tasks without a remoteID are saved together) and aRepeatedRemoteIDReplacesTheStoredRow (two inserts with the same remoteID leave one row, with the second one's title: the upsert, measured).

The second tests the view model, with an in-memory repository or with FailingTaskRepository, a double that fails on every write:

NativeTaskManagerTests/TaskListViewModelTests.swift
import Foundation
import Testing
@testable import NativeTaskManager
 
@MainActor
struct TaskListViewModelTests {
    @Test func startsIdle() {
        let viewModel = AppDependencies.inMemory().makeTaskListViewModel()
 
        #expect(viewModel.state == .idle)
    }
 
    @Test func loadingAnEmptyStoreIsEmpty() {
        let viewModel = AppDependencies.inMemory().makeTaskListViewModel()
 
        viewModel.load()
 
        #expect(viewModel.state == .empty)
        #expect(viewModel.tasks.isEmpty)
    }
 
    @Test func loadingStoredTasksIsLoaded() {
        let viewModel = AppDependencies.inMemory(tasks: [TaskItem(title: "a")]).makeTaskListViewModel()
 
        viewModel.load()
 
        #expect(viewModel.state == .loaded)
        #expect(viewModel.tasks.map(\.title) == ["a"])
    }
 
    @Test func addStoresTheNormalizedDraft() throws {
        let dependencies = AppDependencies.inMemory()
        let viewModel = dependencies.makeTaskListViewModel()
 
        viewModel.add(TaskDraft(title: "  Call Ana  "))
 
        #expect(viewModel.state == .loaded)
        #expect(try dependencies.repository.fetchAll().map(\.title) == ["Call Ana"])
    }
 
    @Test func toggleCompletionIsPersisted() throws {
        let dependencies = AppDependencies.inMemory(tasks: [TaskItem(title: "a")])
        let viewModel = dependencies.makeTaskListViewModel()
        viewModel.load()
 
        viewModel.toggleCompletion(of: try #require(viewModel.tasks.first))
 
        #expect(try dependencies.repository.fetchAll().first?.isCompleted == true)
    }
 
    @Test func updateAppliesTheDraft() throws {
        let dependencies = AppDependencies.inMemory(tasks: [TaskItem(title: "a")])
        let viewModel = dependencies.makeTaskListViewModel()
        viewModel.load()
        let task = try #require(viewModel.tasks.first)
 
        viewModel.update(task, with: TaskDraft(title: "b", notes: "n"))
 
        let stored = try #require(try dependencies.repository.fetchAll().first)
        #expect(stored.title == "b")
        #expect(stored.notes == "n")
    }
 
    @Test func deletingTheLastTaskIsEmpty() throws {
        let viewModel = AppDependencies.inMemory(tasks: [TaskItem(title: "a")]).makeTaskListViewModel()
        viewModel.load()
 
        viewModel.delete(try #require(viewModel.tasks.first))
 
        #expect(viewModel.state == .empty)
    }
 
    @Test func aFailedReadIsFailed() {
        let viewModel = TaskListViewModel(repository: FailingTaskRepository())
 
        viewModel.load()
 
        #expect(viewModel.state == .failed(message: "Your tasks could not be read."))
    }
 
    @Test func aFailedChangeKeepsTheListAndReportsIt() {
        let repository = FailingTaskRepository(failsReads: false)
        let viewModel = TaskListViewModel(repository: repository)
 
        viewModel.add(TaskDraft(title: "a"))
 
        #expect(viewModel.errorMessage == "The change could not be saved.")
        #expect(viewModel.state == .empty)
    }
 
    @Test func filterSelectsByCompletion() {
        let done = TaskItem(title: "done", isCompleted: true)
        let open = TaskItem(title: "open")
        let viewModel = AppDependencies.inMemory(tasks: [done, open]).makeTaskListViewModel()
        viewModel.load()
 
        viewModel.filter = .completed
        #expect(viewModel.visibleTasks.map(\.title) == ["done"])
 
        viewModel.filter = .active
        #expect(viewModel.visibleTasks.map(\.title) == ["open"])
    }
}
 
/// A repository whose writes always fail, and whose reads fail unless told otherwise.
@MainActor
final class FailingTaskRepository: TaskRepository {
    struct Failure: Error {}
    private let failsReads: Bool
 
    init(failsReads: Bool = true) {
        self.failsReads = failsReads
    }
 
    func fetchAll() throws -> [TaskItem] {
        if failsReads { throw Failure() }
        return []
    }
 
    func add(_ task: TaskItem) throws { throw Failure() }
    func delete(_ task: TaskItem) throws { throw Failure() }
    func save() throws { throw Failure() }
}

Try it yourself: ⌘R. The app looks the same as in step 05, and creating and completing tasks still works; what changed is who does it. ⌘U has to count 35 tests.

The list in the simulator with a newly created task, Water the plants, with its unchecked circle, under the title Tasks and the plus button in the bar.
A task created from the form: now the view model saves it, through the repository.

The usual mistake: keeping only the ModelContext and not the ModelContainer. The first version of the repository received the context (init(context:)), and the tests that created the dependencies in a single line, without storing them in a variable, crashed. Xcode only said:

Crash: NativeTaskManager at specialized static Runner._applyScopingTraits(for:testCase:_:)

The ones that stored the dependencies in a variable passed, and that pattern was the clue: the context didn't keep its container alive. Once the temporary AppDependencies was released, the container went away and the context crashed when reading.

It's what I observed with Xcode 27.2, not a documented contract, so the practical rule is to always keep the container. It's the reasoning from "ARC: Who Keeps an Object Alive", and Memory Graph, from "Debugging and Performance", is the tool to see which objects are still alive and who retains them.

Check what you learned. The TaskRepository protocol has a single implementation in the app. What is it for?

Solution

For the tests: a repository that fails on purpose checks what the view model does with a read or write error, something real SwiftData doesn't fail at on request. It doesn't exist to switch databases someday; if an abstraction didn't even have that use, it would be unnecessary.

What to take away: the view draws and reports; the view model decides; the repository stores. And each piece receives what it uses through its initializer.

Download the code for step 06.

Note: a good point for a break: you've done 6 of the 12 steps, about two and a half hours. You already have the architecture; what follows teaches the app to talk to the network.

Step 07: The Network and the Import

Where do the first tasks of someone who just installed the app come from? From the network, once. There are three pieces: the network errors, the client that makes the request, and the import that stores without duplicating.

The API

GET https://jsonplaceholder.typicode.com/todos?userId=1 returns user 1's 20 todos, an array of objects with userId, id, title, and completed. The full resource has 200; filtering by userId leaves a comfortable amount for a list.

The titles are filler text in made-up Latin, like "delectus aut autem". It's the API from "Just Enough HTTP and REST", and the app reads it and never writes to it.

The Errors

Create the NativeTaskManager/Networking/ folder and, inside it:

NativeTaskManager/Networking/APIError.swift
import Foundation
 
/// Everything that can go wrong while fetching the sample todos, in terms the app can act on.
nonisolated enum APIError: Error, Equatable, Sendable {
    case timeout
    case offline
    case cancelled
    case transport(URLError.Code)
    case invalidResponse
    case badStatus(Int)
    case decoding
 
    init(_ error: URLError) {
        switch error.code {
        case .timedOut: self = .timeout
        case .notConnectedToInternet, .networkConnectionLost, .dataNotAllowed: self = .offline
        case .cancelled: self = .cancelled
        default: self = .transport(error.code)
        }
    }
}

APIError translates what can fail into cases the app can do something with: there's no connection, the time ran out, it was cancelled, the server answered with an error code, the response can't be understood. init(_ error: URLError) groups the URLError codes: three of them mean "no connection" to the user. It's Equatable, so the tests can compare the exact case.

The Client

NativeTaskManager/Networking/TodoAPIClient.swift
import Foundation
 
/// The sample API, seen from the app: one read-only call. `nonisolated` and `Sendable` because a
/// client has no reason to be tied to the main actor.
nonisolated protocol TodoAPIClient: Sendable {
    func fetchTodos() async throws -> [RemoteTodo]
}
 
nonisolated struct URLSessionTodoAPIClient: TodoAPIClient {
    static let defaultBaseURL = URL(string: "https://jsonplaceholder.typicode.com")!
 
    let baseURL: URL
    let session: URLSession
    let timeout: TimeInterval
 
    init(baseURL: URL = Self.defaultBaseURL, session: URLSession = .shared, timeout: TimeInterval = 15) {
        self.baseURL = baseURL
        self.session = session
        self.timeout = timeout
    }
 
    /// `GET /todos?userId=1`: JSONPlaceholder's documented filter, 20 todos of one user.
    func makeRequest() -> URLRequest {
        var components = URLComponents(url: baseURL.appending(path: "todos"), resolvingAgainstBaseURL: false)!
        components.queryItems = [URLQueryItem(name: "userId", value: "1")]
        // The default timeout is 60 s; for a small JSON a user is waiting on, 15 s is plenty.
        var request = URLRequest(url: components.url!, timeoutInterval: timeout)
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        return request
    }
 
    func fetchTodos() async throws -> [RemoteTodo] {
        let data: Data
        let response: URLResponse
        do {
            (data, response) = try await session.data(for: makeRequest())
        } catch let error as URLError {
            throw APIError(error)
        } catch is CancellationError {
            throw APIError.cancelled
        }
 
        guard let http = response as? HTTPURLResponse else { throw APIError.invalidResponse }
        guard (200..<300).contains(http.statusCode) else { throw APIError.badStatus(http.statusCode) }
 
        do {
            return try JSONDecoder().decode([RemoteTodo].self, from: data)
        } catch {
            throw APIError.decoding
        }
    }
}
 
/// A fixed, offline client: previews use it, and UI tests will (never the network).
nonisolated struct FixtureTodoAPIClient: TodoAPIClient {
    var todos: [RemoteTodo] = [
        RemoteTodo(userId: 1, id: 1, title: "delectus aut autem", completed: false),
        RemoteTodo(userId: 1, id: 2, title: "quis ut nam facilis et officia qui", completed: false),
        RemoteTodo(userId: 1, id: 4, title: "et porro tempora", completed: true),
    ]
 
    func fetchTodos() async throws -> [RemoteTodo] {
        todos
    }
}

It's the client from "URLSession and Codable" in its app form:

  • A one-method protocol, TodoAPIClient, so the view model doesn't depend on URLSession. There are two implementations: URLSessionTodoAPIClient, the real one, and FixtureTodoAPIClient, which returns three fixed todos without a network. A fixture is fixed test data, written so the result is always the same.
  • The URLSession is injected, with .shared as the default value. The tests pass it a session with a fake protocol.
  • An explicit 15-second timeout. URLRequest's is 60 by default, and it measures inactivity, not the whole download, as you saw in "Robust Networking".
  • The status before the body. First it checks that the response is HTTP and that the code is between 200 and 299; only then does it decode. A 404 can bring a body that isn't the list.
  • Every error, translated. A URLError becomes an APIError, a cancellation of the task becomes .cancelled, and a decoding failure, .decoding.

The protocol and the client are nonisolated and Sendable: an HTTP client has no reason to be tied to the main actor, and its three properties are Sendable.

With Approachable Concurrency, fetchTodos() runs on its caller's actor, the view model; waiting on session.data(for:) suspends the function without blocking the thread. Decoding 20 todos on the main actor isn't noticeable; with large responses you'd mark the implementation @concurrent, as in "Actors and the Main Actor".

The Import

NativeTaskManager/Data/TaskRepository.swift
--- a/NativeTaskManager/Data/TaskRepository.swift
+++ b/NativeTaskManager/Data/TaskRepository.swift
@@ -9,6 +9,8 @@
     func delete(_ task: TaskItem) throws
     /// Persists changes made to tasks that are already stored (toggle, edit).
     func save() throws
+    /// Adds the sample todos not stored yet and returns how many were added.
+    func importTodos(_ todos: [RemoteTodo]) throws -> Int
 }
 
 final class SwiftDataTaskRepository: TaskRepository {
@@ -39,3 +41,21 @@
         try context.save()
     }
 }
+
+extension SwiftDataTaskRepository {
+    /// Idempotent: a todo whose `remoteID` is already stored is skipped, so importing twice adds
+    /// nothing, and a task the user edited keeps the user's version. Imported tasks are local from
+    /// now on; nothing is ever sent back to the sample API.
+    func importTodos(_ todos: [RemoteTodo]) throws -> Int {
+        let imported = try context.fetch(FetchDescriptor<TaskItem>(predicate: #Predicate { $0.remoteID != nil }))
+        var known = Set(imported.compactMap(\.remoteID))
+        var added = 0
+        for todo in todos where !known.contains(todo.id) {
+            context.insert(TaskItem(remote: todo))
+            known.insert(todo.id) // also guards against a repeated id inside one response
+            added += 1
+        }
+        try context.save()
+        return added
+    }
+}

importTodos(_:) is the idempotent import, written out explicitly:

  1. It reads the already stored remoteIDs in one go, with a FetchDescriptor that filters the imported tasks (#Predicate { $0.remoteID != nil }), and puts them in a Set.
  2. It inserts only the todos whose id isn't in the set, and adds each one to the set as it inserts it: that also protects against a repeated id within the same response.
  3. It saves once and returns how many it added.

It's one query for the whole import, not one per todo. And it doesn't rely on the upsert you measured in step 06: if it did, reimporting would overwrite the title the user edited. One consequence, on purpose: if the user deletes an imported task, reimporting brings it back. Importing is "bringing in samples", not syncing.

The View Model, the Dependencies, and the View

NativeTaskManager/Features/TaskList/TaskListViewModel.swift
--- a/NativeTaskManager/Features/TaskList/TaskListViewModel.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListViewModel.swift
@@ -38,9 +38,11 @@
     }
 
     private let repository: any TaskRepository
+    private let apiClient: any TodoAPIClient
 
-    init(repository: any TaskRepository) {
+    init(repository: any TaskRepository, apiClient: any TodoAPIClient) {
         self.repository = repository
+        self.apiClient = apiClient
     }
 
     func load() {
@@ -70,6 +72,18 @@
         perform { try repository.delete(task) }
     }
 
+    /// Downloads the sample todos and stores the ones not imported yet.
+    func importSamples() async {
+        state = .loading
+        do {
+            let todos = try await apiClient.fetchTodos()
+            _ = try repository.importTodos(todos)
+        } catch {
+            errorMessage = "The sample tasks could not be imported."
+        }
+        load()
+    }
+
     /// Runs a change, then re-reads the store so `tasks` always mirrors what is persisted.
     private func perform(_ change: () throws -> Void) {
         do {
NativeTaskManager/App/AppDependencies.swift
--- a/NativeTaskManager/App/AppDependencies.swift
+++ b/NativeTaskManager/App/AppDependencies.swift
@@ -6,16 +6,21 @@
 final class AppDependencies {
     let modelContainer: ModelContainer
     let repository: any TaskRepository
+    let apiClient: any TodoAPIClient
 
-    init(modelContainer: ModelContainer) {
+    init(modelContainer: ModelContainer, apiClient: any TodoAPIClient) {
         self.modelContainer = modelContainer
         self.repository = SwiftDataTaskRepository(container: modelContainer)
+        self.apiClient = apiClient
     }
 
     /// The real app: an on-disk store in the app's container.
     static func live() -> AppDependencies {
         do {
-            return AppDependencies(modelContainer: try ModelContainer(for: TaskItem.self))
+            return AppDependencies(
+                modelContainer: try ModelContainer(for: TaskItem.self),
+                apiClient: URLSessionTodoAPIClient()
+            )
         } catch {
             // Without its store the app cannot do anything useful; failing loudly beats a blank screen.
             fatalError("Could not open the task store: \(error)")
@@ -22,8 +27,12 @@
         }
     }
 
-    /// Previews and tests: a store that lives only in memory, optionally pre-filled.
-    static func inMemory(tasks: [TaskItem] = []) -> AppDependencies {
+    /// Previews and tests: a store that lives only in memory, optionally pre-filled, and an API
+    /// client that never touches the network.
+    static func inMemory(
+        tasks: [TaskItem] = [],
+        apiClient: any TodoAPIClient = FixtureTodoAPIClient()
+    ) -> AppDependencies {
         do {
             let container = try ModelContainer(
                 for: TaskItem.self,
@@ -31,7 +40,7 @@
             )
             tasks.forEach(container.mainContext.insert)
             try container.mainContext.save()
-            return AppDependencies(modelContainer: container)
+            return AppDependencies(modelContainer: container, apiClient: apiClient)
         } catch {
             fatalError("Could not create the in-memory store: \(error)")
         }
@@ -38,6 +47,6 @@
     }
 
     func makeTaskListViewModel() -> TaskListViewModel {
-        TaskListViewModel(repository: repository)
+        TaskListViewModel(repository: repository, apiClient: apiClient)
     }
 }
NativeTaskManager/Features/TaskList/TaskListView.swift
--- a/NativeTaskManager/Features/TaskList/TaskListView.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListView.swift
@@ -13,6 +13,9 @@
                     ToolbarItem(placement: .primaryAction) {
                         Button("Add Task", systemImage: "plus") { isCreating = true }
                     }
+                    ToolbarItem(placement: .secondaryAction) {
+                        importButton
+                    }
                 }
                 .sheet(isPresented: $isCreating) {
                     TaskFormView(isCreating: true) { draft in
@@ -38,11 +41,13 @@
         case .idle, .loading:
             ProgressView()
         case .empty:
-            ContentUnavailableView(
-                "No Tasks",
-                systemImage: "checklist",
-                description: Text("Tap + to add your first task.")
-            )
+            ContentUnavailableView {
+                Label("No Tasks", systemImage: "checklist")
+            } description: {
+                Text("Tap + to add your first task, or import a few samples.")
+            } actions: {
+                importButton
+            }
         case .failed(let message):
             ContentUnavailableView(
                 "Couldn't Load Tasks",
@@ -55,6 +60,12 @@
             }
         }
     }
+
+    private var importButton: some View {
+        Button("Import Sample Tasks", systemImage: "square.and.arrow.down") {
+            Task { await viewModel.importSamples() }
+        }
+    }
 }
 
 #Preview("With tasks") {

The view model receives the client through its initializer, like the repository, and importSamples() is an async function: it asks for the todos with await and stores them. The composition root picks the client: live() uses the real one; inMemory(...), the fixture one.

The view offers "Import Sample Tasks" in two places: as the empty state's action and in the bar's menu (.secondaryAction, the button with the ellipsis). Since the button is a synchronous action, it launches the import with Task { … }. In this step, a failure only puts a message in the alert; step 08 does it properly.

Going deeper

the tests for this step. To test the real client without a network, the session is created with a custom URLProtocol, the mechanism from "Tests: Swift Testing, XCTest, and Test Doubles": the session hands it each request and it answers whatever the test prepared. Create this file in NativeTaskManagerTests/:

NativeTaskManagerTests/StubURLProtocol.swift
import Foundation
import Synchronization
import Testing
 
/// Answers every request of a session built with `makeSession()` with a canned stub, so the API
/// client is tested end to end (URLSession, status codes, decoding) without the network.
final class StubURLProtocol: URLProtocol {
    enum Stub: Sendable {
        case response(status: Int, body: Data)
        case failure(URLError.Code)
    }
 
    private struct State: Sendable {
        var stub: Stub?
        var lastRequest: URLRequest?
    }
 
    private static let state = Mutex(State())
 
    static func stub(_ stub: Stub) {
        state.withLock { $0 = State(stub: stub) }
    }
 
    static var lastRequest: URLRequest? {
        state.withLock { $0.lastRequest }
    }
 
    static func makeSession() -> URLSession {
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [StubURLProtocol.self]
        return URLSession(configuration: configuration)
    }
 
    override class func canInit(with request: URLRequest) -> Bool { true }
    override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
 
    override func startLoading() {
        let request = self.request
        let stub = Self.state.withLock { state in
            state.lastRequest = request
            return state.stub
        }
        switch stub {
        case .response(let status, let body):
            let response = HTTPURLResponse(
                url: request.url!, statusCode: status, httpVersion: "HTTP/1.1",
                headerFields: ["Content-Type": "application/json"]
            )!
            client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
            client?.urlProtocol(self, didLoad: body)
            client?.urlProtocolDidFinishLoading(self)
        case .failure(let code):
            client?.urlProtocol(self, didFailWithError: URLError(code))
        case nil:
            client?.urlProtocol(self, didFailWithError: URLError(.resourceUnavailable))
        }
    }
 
    override func stopLoading() {}
}
 
enum Fixture {
    private final class BundleToken {}
 
    /// A JSON file copied into the test bundle (the Fixtures folder is a synchronized group).
    static func data(_ name: String) throws -> Data {
        let url = try #require(Bundle(for: BundleToken.self).url(forResource: name, withExtension: "json"))
        return try Data(contentsOf: url)
    }
}

The prepared response and the last request live in a Mutex from the Synchronization framework: the session calls the protocol from its own threads, and the Mutex makes that access safe.

To check it while the tests run, Thread Sanitizer (Product › Scheme › Edit Scheme… › Test › Diagnostics) detects data races, as you saw in "Debugging and Performance". The suite that uses it is @Suite(.serialized): since the state is one for all its tests, they run one after another. Fixture.data(_:) loads a JSON from the test bundle.

The JSON goes in a new folder, NativeTaskManagerTests/Fixtures/, created with the Empty File template. It gets into the test bundle just by being in the tests' synchronized folder. It's four todos with JSONPlaceholder's real shape and titles:

NativeTaskManagerTests/Fixtures/todos-user1.json
[
  { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false },
  { "userId": 1, "id": 2, "title": "quis ut nam facilis et officia qui", "completed": false },
  { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false },
  { "userId": 1, "id": 4, "title": "et porro tempora", "completed": true }
]

The client tests: the valid response; that the request is a GET to /todos?userId=1 with Accept: application/json and a 15-second timeout; that 404, 500, and 503 are badStatus; that a broken JSON is decoding; and that a URLError for a timeout or no connection is translated correctly.

NativeTaskManagerTests/URLSessionTodoAPIClientTests.swift
import Foundation
import Testing
@testable import NativeTaskManager
 
/// Serialized: the stub is shared state of the URL loading system.
@Suite(.serialized)
struct URLSessionTodoAPIClientTests {
    private let client = URLSessionTodoAPIClient(
        baseURL: URL(string: "https://api.example.test")!,
        session: StubURLProtocol.makeSession()
    )
 
    @Test func decodesTheTodosOfAValidResponse() async throws {
        StubURLProtocol.stub(.response(status: 200, body: try Fixture.data("todos-user1")))
 
        let todos = try await client.fetchTodos()
 
        #expect(todos.count == 4)
        #expect(todos.first == RemoteTodo(userId: 1, id: 1, title: "delectus aut autem", completed: false))
        #expect(todos.last?.completed == true)
    }
 
    @Test func asksForTheTodosOfUserOne() async throws {
        StubURLProtocol.stub(.response(status: 200, body: Data("[]".utf8)))
 
        _ = try await client.fetchTodos()
 
        let request = try #require(StubURLProtocol.lastRequest)
        #expect(request.httpMethod == "GET")
        #expect(request.url?.absoluteString == "https://api.example.test/todos?userId=1")
        #expect(request.value(forHTTPHeaderField: "Accept") == "application/json")
        #expect(request.timeoutInterval == 15)
    }
 
    @Test(arguments: [404, 500, 503])
    func rejectsANonSuccessStatus(status: Int) async throws {
        StubURLProtocol.stub(.response(status: status, body: Data("{}".utf8)))
 
        await #expect(throws: APIError.badStatus(status)) {
            try await client.fetchTodos()
        }
    }
 
    @Test func reportsInvalidJSONAsDecoding() async throws {
        StubURLProtocol.stub(.response(status: 200, body: Data(#"{"not": "an array"}"#.utf8)))
 
        await #expect(throws: APIError.decoding) {
            try await client.fetchTodos()
        }
    }
 
    @Test func mapsATimeout() async throws {
        StubURLProtocol.stub(.failure(.timedOut))
 
        await #expect(throws: APIError.timeout) {
            try await client.fetchTodos()
        }
    }
 
    @Test func mapsNoConnectionToOffline() async throws {
        StubURLProtocol.stub(.failure(.notConnectedToInternet))
 
        await #expect(throws: APIError.offline) {
            try await client.fetchTodos()
        }
    }
}

The import tests, on an in-memory store: importing twice adds nothing, an id repeated in the same response is saved once, a local edit is never overwritten, and the local tasks aren't touched.

NativeTaskManagerTests/TaskImportTests.swift
import Foundation
import Testing
@testable import NativeTaskManager
 
@MainActor
struct TaskImportTests {
    private let dependencies = AppDependencies.inMemory()
    private var repository: any TaskRepository { dependencies.repository }
 
    private let todos = [
        RemoteTodo(userId: 1, id: 1, title: "first", completed: false),
        RemoteTodo(userId: 1, id: 2, title: "second", completed: true),
    ]
 
    @Test func importAddsEveryNewTodo() throws {
        let added = try repository.importTodos(todos)
 
        #expect(added == 2)
        #expect(Set(try repository.fetchAll().compactMap(\.remoteID)) == [1, 2])
    }
 
    @Test func importingTwiceAddsNothingTheSecondTime() throws {
        _ = try repository.importTodos(todos)
 
        let added = try repository.importTodos(todos)
 
        #expect(added == 0)
        #expect(try repository.fetchAll().count == 2)
    }
 
    @Test func aRepeatedIDInOneResponseIsStoredOnce() throws {
        let added = try repository.importTodos(todos + todos)
 
        #expect(added == 2)
    }
 
    @Test func importNeverOverwritesALocalEdit() throws {
        _ = try repository.importTodos(todos)
        let task = try #require(try repository.fetchAll().first { $0.remoteID == 1 })
        task.title = "renamed by the user"
        try repository.save()
 
        _ = try repository.importTodos(todos)
 
        #expect(try repository.fetchAll().first { $0.remoteID == 1 }?.title == "renamed by the user")
    }
 
    @Test func importLeavesLocalTasksAlone() throws {
        try repository.add(TaskItem(title: "mine"))
 
        _ = try repository.importTodos(todos)
 
        #expect(try repository.fetchAll().count == 3)
    }
 
    @Test func theViewModelImportsFromTheClient() async {
        let viewModel = dependencies.makeTaskListViewModel()
 
        await viewModel.importSamples()
 
        #expect(viewModel.state == .loaded)
        #expect(viewModel.tasks.count == FixtureTodoAPIClient().todos.count)
    }
}

And since the protocol and the view model's initializer changed, the tests from step 06 are updated: FailingTaskRepository gains importTodos, and the view model receives a client.

NativeTaskManagerTests/TaskListViewModelTests.swift
--- a/NativeTaskManagerTests/TaskListViewModelTests.swift
+++ b/NativeTaskManagerTests/TaskListViewModelTests.swift
@@ -71,7 +71,7 @@
     }
 
     @Test func aFailedReadIsFailed() {
-        let viewModel = TaskListViewModel(repository: FailingTaskRepository())
+        let viewModel = TaskListViewModel(repository: FailingTaskRepository(), apiClient: FixtureTodoAPIClient())
 
         viewModel.load()
 
@@ -80,7 +80,7 @@
 
     @Test func aFailedChangeKeepsTheListAndReportsIt() {
         let repository = FailingTaskRepository(failsReads: false)
-        let viewModel = TaskListViewModel(repository: repository)
+        let viewModel = TaskListViewModel(repository: repository, apiClient: FixtureTodoAPIClient())
 
         viewModel.add(TaskDraft(title: "a"))
 
@@ -120,4 +120,5 @@
     func add(_ task: TaskItem) throws { throw Failure() }
     func delete(_ task: TaskItem) throws { throw Failure() }
     func save() throws { throw Failure() }
+    func importTodos(_ todos: [RemoteTodo]) throws -> Int { throw Failure() }
 }

Try it yourself: ⌘R with the Mac connected to the internet. If the list is empty, tap "Import Sample Tasks": 20 tasks with titles in made-up Latin appear, some already completed. Tap it again from the bar's menu: no new task appears. ⌘U has to count 47 tests, and none of them goes out to the network.

The usual mistake: using #require in StubURLProtocol.swift without import Testing in that file. With the member import visibility the template turns on, each file imports its own, and the compiler gave:

error: no macro named 'require'
warning: no calls to throwing functions occur within 'try' expression [#UnnecessaryEffectMarker]

The warning is a consequence of the error: without the macro, the try doesn't wrap anything that throws. You fix it by adding import Testing at the top of the file.

Check what you learned. If reimporting doesn't duplicate anything, why isn't the @Attribute(.unique) on remoteID enough, so that you have to look before inserting?

Solution

Because SwiftData, faced with a repeated unique value, replaces the stored row with the new one: step 06's aRepeatedRemoteIDReplacesTheStoredRow test measured it. If the user edited an imported task, reimporting would overwrite it with the API's title. By looking first, what's already there is skipped and local wins.

What to take away: a network client receives its session, checks the status before decoding, and translates each error into something the app can say; the import looks before it inserts.

Download the code for step 07.

Step 08: Loading, Empty, Success, and Error

What does the user see when the network fails? Until now, a generic alert. This step gives the import its full set of states, a button to retry, and cancellation when the screen disappears.

Messages That Say What to Do

NativeTaskManager/Networking/APIError.swift
--- a/NativeTaskManager/Networking/APIError.swift
+++ b/NativeTaskManager/Networking/APIError.swift
@@ -19,3 +19,17 @@
         }
     }
 }
+
+extension APIError {
+    /// What the user reads. It says what happened and what to do, never a status line or a type name.
+    var userMessage: String {
+        switch self {
+        case .offline: "You seem to be offline. Check your connection and try again."
+        case .timeout: "The sample server took too long to answer. Try again in a moment."
+        case .badStatus(let code) where code >= 500: "The sample server is having trouble (error \(code)). Try again later."
+        case .badStatus(let code): "The sample server refused the request (error \(code))."
+        case .invalidResponse, .decoding: "The sample server sent an answer the app does not understand."
+        case .transport, .cancelled: "The sample tasks could not be downloaded."
+        }
+    }
+}

userMessage gives one message per case. Each one says what happened and what the user can do ("You seem to be offline. Check your connection and try again."), and none of them shows a type name or an HTTP status line. The error code appears in parentheses when it helps to ask for support.

The Import's States

NativeTaskManager/Features/TaskList/TaskListViewModel.swift
--- a/NativeTaskManager/Features/TaskList/TaskListViewModel.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListViewModel.swift
@@ -30,9 +30,14 @@
     private(set) var state: LoadState = .idle
     private(set) var tasks: [TaskItem] = []
     var filter: Filter = .all
-    /// A failed change (save, delete). The list stays on screen; the view shows an alert.
+    /// A failed change or import while tasks are on screen. The list stays; the view shows an alert.
     var errorMessage: String?
+    private(set) var isImporting = false
 
+    private enum RetryAction { case load, importSamples }
+    private var retryAction = RetryAction.load
+    private var importTask: Task<Void, Never>?
+
     var visibleTasks: [TaskItem] {
         tasks.filter(filter.includes)
     }
@@ -50,6 +55,7 @@
             tasks = try repository.fetchAll()
             state = tasks.isEmpty ? .empty : .loaded
         } catch {
+            retryAction = .load
             state = .failed(message: "Your tasks could not be read.")
         }
     }
@@ -73,17 +79,65 @@
     }
 
     /// Downloads the sample todos and stores the ones not imported yet.
+    ///
+    /// With an empty list the whole screen shows the progress and, on failure, an error with a
+    /// retry. With tasks on screen the list stays put and a failure is an alert: the network
+    /// failing is never a reason to hide data the user already has.
     func importSamples() async {
-        state = .loading
+        guard !isImporting else { return }
+        isImporting = true
+        defer { isImporting = false }
+        let hadTasks = !tasks.isEmpty
+        if !hadTasks { state = .loading }
+
         do {
-            let todos = try await apiClient.fetchTodos()
-            _ = try repository.importTodos(todos)
+            _ = try repository.importTodos(try await apiClient.fetchTodos())
+            load()
+        } catch APIError.cancelled, is CancellationError {
+            load() // the user left; nothing to report
         } catch {
-            errorMessage = "The sample tasks could not be imported."
+            let message = (error as? APIError)?.userMessage ?? "The sample tasks could not be saved."
+            load()
+            if hadTasks {
+                errorMessage = message
+            } else {
+                retryAction = .importSamples
+                state = .failed(message: message)
+            }
         }
-        load()
     }
 
+    /// Starts an import the view can cancel, or returns the one already running.
+    /// The task is returned so tests can await it.
+    @discardableResult
+    func startImport() -> Task<Void, Never> {
+        if let importTask { return importTask }
+        let task = Task {
+            await importSamples()
+            importTask = nil
+        }
+        importTask = task
+        return task
+    }
+
+    /// Called when the screen goes away: the URLSession request is cancelled with the task.
+    func cancelImport() {
+        importTask?.cancel()
+        importTask = nil
+    }
+
+    /// The "Try Again" of the error state: repeats whatever failed.
+    @discardableResult
+    func retry() -> Task<Void, Never>? {
+        switch retryAction {
+        case .load:
+            load()
+            return nil
+        case .importSamples:
+            return startImport()
+        }
+    }
+
     /// Runs a change, then re-reads the store so `tasks` always mirrors what is persisted.
     private func perform(_ change: () throws -> Void) {
         do {

importSamples() decides based on what the user already has on screen:

  • With the list empty, the whole screen goes to .loading and ends in .loaded, .empty, or .failed(message:), with the message and the option to retry.
  • With tasks on screen, the list stays where it is and a failure is an alert.
  • isImporting disables the button while an import is in progress.
  • retry() repeats whatever failed, reading the store or importing, according to retryAction, a private enum the view model records when it fails.

Cancellation

The import is now a task the view model keeps. startImport() creates it, or returns the one already in progress: there's only one at a time. cancelImport() cancels it, and the view calls it in .onDisappear.

Cancelling the task cancels the URLSession request, which throws a URLError with the code .cancelled, as you measured in "Tasks and Structured Concurrency"; the client translates it to APIError.cancelled. A cancelled import doesn't show any error.

startImport() and retry() carry @discardableResult, which tells the compiler not to warn if the caller ignores the returned value: the button ignores the task, and the tests await it.

Why a stored task and not SwiftUI's .task modifier, which cancels itself when the view disappears? Because a button can't launch work inside .task without tricks, and the stored task works the same for the button and for the launch in step 09.

In this app you can't trigger the cancellation by hand: the list is the root of the navigation. The .onDisappear documentation only says it runs after the view disappears; in this app, I only observed it when the scene was destroyed, and sending the app to the background didn't trigger it. The aCancelledImportReportsNothing test checks it, and the mechanism is the same one you'd use if the list were deeper in a navigation.

The View

NativeTaskManager/Features/TaskList/TaskListView.swift
--- a/NativeTaskManager/Features/TaskList/TaskListView.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListView.swift
@@ -33,13 +33,16 @@
                 )
         }
         .task { viewModel.load() }
+        .onDisappear { viewModel.cancelImport() }
     }
 
     @ViewBuilder
     private var content: some View {
         switch viewModel.state {
-        case .idle, .loading:
+        case .idle:
             ProgressView()
+        case .loading:
+            ProgressView("Importing sample tasks…")
         case .empty:
             ContentUnavailableView {
                 Label("No Tasks", systemImage: "checklist")
@@ -49,11 +52,14 @@
                 importButton
             }
         case .failed(let message):
-            ContentUnavailableView(
-                "Couldn't Load Tasks",
-                systemImage: "exclamationmark.triangle",
-                description: Text(message)
-            )
+            ContentUnavailableView {
+                Label("Something Went Wrong", systemImage: "exclamationmark.triangle")
+            } description: {
+                Text(message)
+            } actions: {
+                Button("Try Again") { viewModel.retry() }
+                    .buttonStyle(.borderedProminent)
+            }
         case .loaded:
             List(viewModel.visibleTasks) { task in
                 TaskRowView(task: task, onToggle: { viewModel.toggleCompletion(of: task) })
@@ -63,8 +69,9 @@
 
     private var importButton: some View {
         Button("Import Sample Tasks", systemImage: "square.and.arrow.down") {
-            Task { await viewModel.importSamples() }
+            viewModel.startImport()
         }
+        .disabled(viewModel.isImporting)
     }
 }
 

.loading shows a ProgressView with text ("Importing sample tasks…"), not just the spinner: people who use VoiceOver also know what they're waiting for. The error is another ContentUnavailableView, this time with a "Try Again" button. In this step that button uses .borderedProminent; in step 12, the accessibility audit fails it for contrast and it changes.

Going deeper

the tests for this step. To test the states you need fake clients that answer in order, fail, or never answer, and in this step they live next to their tests:

NativeTaskManagerTests/ImportStateTests.swift
import Foundation
import Testing
@testable import NativeTaskManager
 
/// Answers with scripted results, in order. Before answering it runs `whileFetching` on the main
/// actor, so a test can look at the view model in the middle of an import.
actor ScriptedTodoAPIClient: TodoAPIClient {
    private var results: [Result<[RemoteTodo], APIError>]
    private let whileFetching: @MainActor @Sendable () -> Void
    private(set) var calls = 0
 
    init(_ results: [Result<[RemoteTodo], APIError>], whileFetching: @escaping @MainActor @Sendable () -> Void = {}) {
        self.results = results
        self.whileFetching = whileFetching
    }
 
    func fetchTodos() async throws -> [RemoteTodo] {
        calls += 1
        await whileFetching()
        return try results.removeFirst().get()
    }
}
 
/// Never answers on its own: it waits until its task is cancelled.
struct HangingTodoAPIClient: TodoAPIClient {
    func fetchTodos() async throws -> [RemoteTodo] {
        try await Task.sleep(for: .seconds(60))
        return []
    }
}
 
@MainActor
final class StateProbe {
    var viewModel: TaskListViewModel?
    var seen: [TaskListViewModel.LoadState] = []
}
 
@MainActor
struct ImportStateTests {
    private let todos = [RemoteTodo(userId: 1, id: 1, title: "first", completed: false)]
 
    private func makeViewModel(_ client: any TodoAPIClient, tasks: [TaskItem] = []) -> TaskListViewModel {
        let viewModel = AppDependencies.inMemory(tasks: tasks, apiClient: client).makeTaskListViewModel()
        viewModel.load()
        return viewModel
    }
 
    @Test func anEmptyListShowsLoadingThenLoaded() async {
        let probe = StateProbe()
        let client = ScriptedTodoAPIClient([.success(todos)]) {
            if let state = probe.viewModel?.state { probe.seen.append(state) }
        }
        let viewModel = makeViewModel(client)
        probe.viewModel = viewModel
 
        await viewModel.importSamples()
 
        #expect(probe.seen == [.loading])
        #expect(viewModel.state == .loaded)
        #expect(!viewModel.isImporting)
    }
 
    @Test func aFailureOnAnEmptyListIsTheErrorState() async {
        let viewModel = makeViewModel(ScriptedTodoAPIClient([.failure(.offline)]))
 
        await viewModel.importSamples()
 
        #expect(viewModel.state == .failed(message: APIError.offline.userMessage))
        #expect(viewModel.errorMessage == nil)
    }
 
    @Test func retryAfterAFailureImports() async {
        let client = ScriptedTodoAPIClient([.failure(.timeout), .success(todos)])
        let viewModel = makeViewModel(client)
        await viewModel.importSamples()
 
        await viewModel.retry()?.value
 
        #expect(viewModel.state == .loaded)
        #expect(viewModel.tasks.map(\.remoteID) == [1])
        #expect(await client.calls == 2)
    }
 
    @Test func aFailureWithTasksOnScreenKeepsTheListAndAlerts() async {
        let viewModel = makeViewModel(ScriptedTodoAPIClient([.failure(.badStatus(500))]), tasks: [TaskItem(title: "mine")])
        let probe = viewModel.state
 
        await viewModel.importSamples()
 
        #expect(probe == .loaded)
        #expect(viewModel.state == .loaded)
        #expect(viewModel.tasks.map(\.title) == ["mine"])
        #expect(viewModel.errorMessage == APIError.badStatus(500).userMessage)
    }
 
    @Test func aCancelledImportReportsNothing() async {
        let viewModel = makeViewModel(HangingTodoAPIClient())
 
        let task = viewModel.startImport()
        viewModel.cancelImport()
        await task.value
 
        #expect(viewModel.state == .empty)
        #expect(viewModel.errorMessage == nil)
        #expect(!viewModel.isImporting)
    }
 
    @Test func startingTwiceReusesTheRunningImport() async {
        let viewModel = makeViewModel(ScriptedTodoAPIClient([.success(todos)]))
 
        let first = viewModel.startImport()
        let second = viewModel.startImport()
        await first.value
 
        #expect(first == second)
        #expect(viewModel.state == .loaded)
    }
 
    @Test(arguments: [
        (APIError.offline, "offline"),
        (.timeout, "too long"),
        (.badStatus(503), "error 503"),
        (.badStatus(404), "refused"),
        (.decoding, "does not understand"),
    ])
    func messagesSayWhatHappened(error: APIError, fragment: String) {
        #expect(error.userMessage.contains(fragment))
    }
}

ScriptedTodoAPIClient is an actor that returns the results it's given, in order. Before answering, it runs a closure on the main actor that lets the test look at the state halfway through the import. StateProbe is a main-actor class that records what it saw, and HangingTodoAPIClient waits sixty seconds until it's cancelled. The tests:

  • during the request the state is .loading, and at the end .loaded;
  • a failure with the list empty is .failed, and retrying imports;
  • a failure with tasks on screen keeps the list and shows the alert;
  • a cancelled import reports nothing;
  • two startImport() calls return the same task;
  • each message says what it has to say.

Try it yourself: to see the error, the app has to fail to import with the list empty. Delete the app from the simulator (press and hold its icon › Remove App), turn off the Mac's Wi-Fi or unplug its cable, and launch the app with ⌘R.

Tap "Import Sample Tasks": you'll see the spinner with its text and, when it fails, the error message with "Try Again". Reconnect the Mac and tap "Try Again": the 20 tasks arrive. (In step 12 there's an argument that opens the app straight into this error.) ⌘U has to count 54 tests.

The usual mistake: having a test find a design error, not a code error. The first version of startImport() cancelled the previous import and started another one. The retry test called retry(), which already started one, and then startImport(): the second cancelled the first and the test failed with

Expectation failed: viewModel.state == .loaded

The fix was the "one at a time" rule: startImport() returns the import in progress if there is one, and the startingTwiceReusesTheRunningImport test pins it down.

Going deeper

a test that passes doesn't always test something. I wrote a reentrancy test that launched a second importSamples() in a task, from the fake client's closure. It passed, but it would have passed just the same without the isImporting guard: the order in which that task runs isn't guaranteed, and the assertion was evaluated first. I removed it. Before you trust a new test, break the code it protects on purpose and see whether it fails.

Check what you learned. A user with 20 tasks taps "Import Sample Tasks" in the bar's menu, with no connection. What do they see?

Solution

Their 20 tasks, untouched, and an alert with "You seem to be offline. Check your connection and try again.". With tasks on screen, an import failure never replaces the list with the error state.

What to take away: every failure has a message that says what to do, and a failure never hides the data the user already has.

Download the code for step 08.

Note: a good point for another break: you've done 8 of the 12 steps, about three and a half hours. What's left makes the app work without a network from the second launch on, completes it, and tests it end to end.

Step 09: Persistence and Caching

What happens the second time you open the app, now without a network? It should work the same. The tasks have lived in SwiftData since step 04; this step makes the role of each layer explicit: the network seeds the data once, and the local store is the source of truth, the place whose contents rule when there's doubt.

The First-Launch Import

NativeTaskManager/Features/TaskList/TaskListViewModel.swift
--- a/NativeTaskManager/Features/TaskList/TaskListViewModel.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListViewModel.swift
@@ -33,6 +33,9 @@
     /// A failed change or import while tasks are on screen. The list stays; the view shows an alert.
     var errorMessage: String?
     private(set) var isImporting = false
+    /// Whether the samples were imported once already. Stored, not computed from UserDefaults,
+    /// so SwiftUI observes it (the button reads "Reimport" afterwards).
+    private(set) var hasImportedSamples: Bool
 
     private enum RetryAction { case load, importSamples }
     private var retryAction = RetryAction.load
@@ -44,12 +47,27 @@
 
     private let repository: any TaskRepository
     private let apiClient: any TodoAPIClient
+    private let defaults: UserDefaults
 
-    init(repository: any TaskRepository, apiClient: any TodoAPIClient) {
+    static let didImportSamplesKey = "didImportSampleTasks"
+
+    init(repository: any TaskRepository, apiClient: any TodoAPIClient, defaults: UserDefaults) {
         self.repository = repository
         self.apiClient = apiClient
+        self.defaults = defaults
+        self.hasImportedSamples = defaults.bool(forKey: Self.didImportSamplesKey)
     }
 
+    /// The screen appeared: read the store and, on the very first launch, bring in the samples.
+    /// The flag is set only after an import succeeds, so a failed first import is tried again on
+    /// the next launch; and an install that already has tasks is never filled with samples.
+    func onAppear() {
+        load()
+        if !hasImportedSamples, state == .empty {
+            startImport()
+        }
+    }
+
     func load() {
         do {
             tasks = try repository.fetchAll()
@@ -92,6 +110,8 @@
 
         do {
             _ = try repository.importTodos(try await apiClient.fetchTodos())
+            defaults.set(true, forKey: Self.didImportSamplesKey)
+            hasImportedSamples = true
             load()
         } catch APIError.cancelled, is CancellationError {
             load() // the user left; nothing to report
@@ -112,6 +132,7 @@
     @discardableResult
     func startImport() -> Task<Void, Never> {
         if let importTask { return importTask }
+        if tasks.isEmpty { state = .loading } // now, not on the task's first tick: no empty-state flash
         let task = Task {
             await importSamples()
             importTask = nil

onAppear() reads the store and, if it has never imported and there are no tasks, starts the import on its own. The "already imported" flag is stored in UserDefaults, the place for small settings from "Where Data Lives", with three rules:

  • It's written only if the import finished well. If the first launch was without a network, the next one tries again.
  • An installation with tasks doesn't get filled with samples, even if the flag isn't there.
  • hasImportedSamples is a stored property, initialized from UserDefaults. Observation tracks the object's stored properties; a computed one derived from them, like visibleTasks, also notifies, because it reads those properties. One that read UserDefaults wouldn't: UserDefaults isn't observable, and the button wouldn't find out it should say "Reimport Sample Tasks".

startImport() sets .loading at the very moment it's called, if the list is empty. Before, the task did it when it started running, and in between you'd have seen one frame of the empty state.

The View Starts the Import

NativeTaskManager/Features/TaskList/TaskListView.swift
--- a/NativeTaskManager/Features/TaskList/TaskListView.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListView.swift
@@ -32,7 +32,7 @@
                     message: { Text(viewModel.errorMessage ?? "") }
                 )
         }
-        .task { viewModel.load() }
+        .task { viewModel.onAppear() }
         .onDisappear { viewModel.cancelImport() }
     }
 
@@ -68,7 +68,10 @@
     }
 
     private var importButton: some View {
-        Button("Import Sample Tasks", systemImage: "square.and.arrow.down") {
+        Button(
+            viewModel.hasImportedSamples ? "Reimport Sample Tasks" : "Import Sample Tasks",
+            systemImage: "square.and.arrow.down"
+        ) {
             viewModel.startImport()
         }
         .disabled(viewModel.isImporting)

The view calls onAppear() instead of load(), and the button changes its text after the first import: "Reimport Sample Tasks". Without this change, the first-launch import never happens.

The Process's Dependencies

NativeTaskManager/App/AppDependencies.swift
--- a/NativeTaskManager/App/AppDependencies.swift
+++ b/NativeTaskManager/App/AppDependencies.swift
@@ -7,11 +7,13 @@
     let modelContainer: ModelContainer
     let repository: any TaskRepository
     let apiClient: any TodoAPIClient
+    let defaults: UserDefaults
 
-    init(modelContainer: ModelContainer, apiClient: any TodoAPIClient) {
+    init(modelContainer: ModelContainer, apiClient: any TodoAPIClient, defaults: UserDefaults) {
         self.modelContainer = modelContainer
         self.repository = SwiftDataTaskRepository(container: modelContainer)
         self.apiClient = apiClient
+        self.defaults = defaults
     }
 
     /// The real app: an on-disk store in the app's container.
@@ -19,7 +21,8 @@
         do {
             return AppDependencies(
                 modelContainer: try ModelContainer(for: TaskItem.self),
-                apiClient: URLSessionTodoAPIClient()
+                apiClient: URLSessionTodoAPIClient(),
+                defaults: .standard
             )
         } catch {
             // Without its store the app cannot do anything useful; failing loudly beats a blank screen.
@@ -27,11 +30,12 @@
         }
     }
 
-    /// Previews and tests: a store that lives only in memory, optionally pre-filled, and an API
-    /// client that never touches the network.
+    /// Previews and tests: a store that lives only in memory, optionally pre-filled, an API client
+    /// that never touches the network and, unless given, a fresh UserDefaults suite of its own.
     static func inMemory(
         tasks: [TaskItem] = [],
-        apiClient: any TodoAPIClient = FixtureTodoAPIClient()
+        apiClient: any TodoAPIClient = FixtureTodoAPIClient(),
+        defaults: UserDefaults? = nil
     ) -> AppDependencies {
         do {
             let container = try ModelContainer(
@@ -40,13 +44,26 @@
             )
             tasks.forEach(container.mainContext.insert)
             try container.mainContext.save()
-            return AppDependencies(modelContainer: container, apiClient: apiClient)
+            return AppDependencies(
+                modelContainer: container,
+                apiClient: apiClient,
+                defaults: defaults ?? UserDefaults(suiteName: "in-memory-\(UUID().uuidString)")!
+            )
         } catch {
             fatalError("Could not create the in-memory store: \(error)")
         }
     }
 
+    /// The dependencies for this process. Tests never reach the network or the real store:
+    /// UI tests launch the app with `-ui-testing`, and unit tests run inside the app, which
+    /// XCTest marks with `XCTestConfigurationFilePath` in the environment.
+    static func forCurrentProcess(_ process: ProcessInfo = .processInfo) -> AppDependencies {
+        let isUITesting = process.arguments.contains("-ui-testing")
+        let isHostingUnitTests = process.environment["XCTestConfigurationFilePath"] != nil
+        return isUITesting || isHostingUnitTests ? .inMemory() : .live()
+    }
+
     func makeTaskListViewModel() -> TaskListViewModel {
-        TaskListViewModel(repository: repository, apiClient: apiClient)
+        TaskListViewModel(repository: repository, apiClient: apiClient, defaults: defaults)
     }
 }
NativeTaskManager/NativeTaskManagerApp.swift
--- a/NativeTaskManager/NativeTaskManagerApp.swift
+++ b/NativeTaskManager/NativeTaskManagerApp.swift
@@ -6,7 +6,7 @@
     @State private var viewModel: TaskListViewModel
 
     init() {
-        let dependencies = AppDependencies.live()
+        let dependencies = AppDependencies.forCurrentProcess()
         self.dependencies = dependencies
         _viewModel = State(initialValue: dependencies.makeTaskListViewModel())
     }

UserDefaults is injected too: live() uses .standard, and inMemory(...) creates its own suite, a UserDefaults with its own name, separate from .standard, so each test has its own flags.

forCurrentProcess() solves a problem that gives no warning. With the automatic import, launching the app already goes out to the network, and the tests launch the app twice: the unit tests run inside the app, which is their test host (the process they're loaded into), and the UI tests launch it to drive it. Without this change, every test run would ask JSONPlaceholder for data. forCurrentProcess() picks the in-memory store and the fixture client in two cases:

  • if the process received the launch argument -ui-testing, a piece of text passed to the app when it's launched and that it reads in ProcessInfo.processInfo.arguments;
  • if the process's environment has the XCTestConfigurationFilePath variable, which XCTest sets when it loads the tests inside the app. It's not a documented contract: I saw it with a temporary test that printed the host's variables.

These test modes also stay in the version you publish; step 12 says how to leave them in development only.

The HTTP Cache

NativeTaskManager/Networking/TodoAPIClient.swift
--- a/NativeTaskManager/Networking/TodoAPIClient.swift
+++ b/NativeTaskManager/Networking/TodoAPIClient.swift
@@ -23,8 +23,11 @@
     func makeRequest() -> URLRequest {
         var components = URLComponents(url: baseURL.appending(path: "todos"), resolvingAgainstBaseURL: false)!
         components.queryItems = [URLQueryItem(name: "userId", value: "1")]
+        // HTTP caching is left to URLCache and the server: JSONPlaceholder answers with
+        // `Cache-Control: max-age=43200` and an ETag, and `.useProtocolCachePolicy` honors both.
+        // No cache layer of our own: SwiftData already keeps every imported task offline.
         // The default timeout is 60 s; for a small JSON a user is waiting on, 15 s is plenty.
-        var request = URLRequest(url: components.url!, timeoutInterval: timeout)
+        var request = URLRequest(url: components.url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: timeout)
         request.setValue("application/json", forHTTPHeaderField: "Accept")
         return request
     }

The request declares .useProtocolCachePolicy, the default value: writing it makes clear that the cache is decided by the server and URLCache, as in "Offline, Caching, and Invalidation".

In practice, with this API, a "Reimport" costs a small request the server answers with 304 ("not modified"), not a full download, and without a network it fails. This step's comment says something more optimistic; step 12 corrects it.

Going deeper

JSONPlaceholder's cache headers. A header is a line of metadata that comes with the response. These are the ones for /todos?userId=1, checked on November 23, 2026:

curl -sI 'https://jsonplaceholder.typicode.com/todos?userId=1'
HTTP/2 200
cache-control: max-age=43200
etag: W/"8df-BI33H3JkF5x/twg0KTe/qy2U04I"
expires: -1
pragma: no-cache

max-age=43200 allows reusing the response for 12 hours, but Expires: -1 and Pragma: no-cache push toward revalidating. On macOS 27.2, with .useProtocolCachePolicy, a second request didn't come from the cache as fresh: URLSession revalidated it with the ETag, and the server answered 304 (I didn't repeat it in the simulator). You can see the revalidation yourself, by asking with the tag:

curl -sI -H 'If-None-Match: W/"8df-BI33H3JkF5x/twg0KTe/qy2U04I"' 'https://jsonplaceholder.typicode.com/todos?userId=1'
HTTP/2 304

There's no custom cache layer on top: what was imported is already in SwiftData, which is the app's cache. I ruled out two alternatives: .reloadIgnoringLocalCacheData on every reimport always downloads the whole body, and a hand-made disk cache would have nothing to store that SwiftData doesn't.

Going deeper

the tests for this step. The first-launch ones go in a new file, which also defines UserDefaults.ephemeralSuite() (a suite with a unique name per test) and the host test:

NativeTaskManagerTests/FirstLaunchImportTests.swift
import Foundation
import Testing
@testable import NativeTaskManager
 
extension UserDefaults {
    /// A suite of its own for one test: tests run in parallel and must not share flags.
    static func ephemeralSuite() -> UserDefaults {
        UserDefaults(suiteName: "tests-\(UUID().uuidString)")!
    }
}
 
@MainActor
struct FirstLaunchImportTests {
    private let todos = [
        RemoteTodo(userId: 1, id: 1, title: "first", completed: false),
        RemoteTodo(userId: 1, id: 2, title: "second", completed: true),
    ]
    private let defaults = UserDefaults.ephemeralSuite()
 
    private func launch(_ client: any TodoAPIClient, tasks: [TaskItem] = []) -> TaskListViewModel {
        AppDependencies.inMemory(tasks: tasks, apiClient: client, defaults: defaults).makeTaskListViewModel()
    }
 
    @Test func theFirstLaunchImportsOnItsOwn() async {
        let viewModel = launch(ScriptedTodoAPIClient([.success(todos)]))
 
        viewModel.onAppear()
        #expect(viewModel.state == .loading) // synchronously: no flash of the empty state
        await viewModel.startImport().value // the import already running
 
        #expect(viewModel.tasks.count == 2)
        #expect(defaults.bool(forKey: TaskListViewModel.didImportSamplesKey))
        #expect(viewModel.hasImportedSamples)
    }
 
    @Test func aLaterLaunchDoesNotImportAgain() async {
        defaults.set(true, forKey: TaskListViewModel.didImportSamplesKey)
        let client = ScriptedTodoAPIClient([.success(todos)])
        let viewModel = launch(client)
 
        viewModel.onAppear()
 
        #expect(viewModel.state == .empty)
        #expect(await client.calls == 0)
    }
 
    @Test func aFailedFirstImportIsTriedOnTheNextLaunch() async {
        let first = launch(ScriptedTodoAPIClient([.failure(.offline)]))
        first.onAppear()
        await first.startImport().value
        #expect(!defaults.bool(forKey: TaskListViewModel.didImportSamplesKey))
 
        let next = launch(ScriptedTodoAPIClient([.success(todos)]))
        next.onAppear()
        await next.startImport().value
 
        #expect(next.state == .loaded)
        #expect(defaults.bool(forKey: TaskListViewModel.didImportSamplesKey))
    }
 
    @Test func anInstallWithTasksIsNotFilledWithSamples() async {
        let client = ScriptedTodoAPIClient([.success(todos)])
        let viewModel = launch(client, tasks: [TaskItem(title: "mine")])
 
        viewModel.onAppear()
 
        #expect(viewModel.tasks.map(\.title) == ["mine"])
        #expect(await client.calls == 0)
    }
 
    @Test func reimportingNeverDuplicates() async {
        let client = ScriptedTodoAPIClient([.success(todos), .success(todos)])
        let viewModel = launch(client)
 
        await viewModel.startImport().value
        await viewModel.startImport().value
 
        #expect(await client.calls == 2)
        #expect(viewModel.tasks.count == 2)
        #expect(Set(viewModel.tasks.compactMap(\.remoteID)) == [1, 2])
    }
 
    @Test func reimportBringsBackADeletedSample() async throws {
        let viewModel = launch(ScriptedTodoAPIClient([.success(todos), .success(todos)]))
        await viewModel.startImport().value
        viewModel.delete(try #require(viewModel.tasks.first { $0.remoteID == 1 }))
 
        await viewModel.startImport().value
 
        #expect(Set(viewModel.tasks.compactMap(\.remoteID)) == [1, 2])
    }
}
 
@MainActor
struct ProcessDependenciesTests {
    @Test func theUnitTestHostNeverUsesTheLiveClient() {
        // These tests run inside the app; its launch must not have reached the network.
        #expect(AppDependencies.forCurrentProcess().apiClient is FixtureTodoAPIClient)
    }
}

The first test calls onAppear() and checks on the next line that the state is already .loading: no frame of the empty state. Then it awaits the import in progress and checks the tasks and the flag. The rest:

  • a later launch doesn't call the client;
  • a failed first attempt doesn't set the flag, and the next launch retries;
  • an installation with tasks doesn't receive samples;
  • reimporting doesn't duplicate, and brings back a deleted sample;
  • the test host doesn't use the real client.

Each test uses its own suite, because Swift Testing runs the tests in parallel and they can't share flags.

The client test pins the request's cache policy:

NativeTaskManagerTests/URLSessionTodoAPIClientTests.swift
--- a/NativeTaskManagerTests/URLSessionTodoAPIClientTests.swift
+++ b/NativeTaskManagerTests/URLSessionTodoAPIClientTests.swift
@@ -30,6 +30,7 @@
         #expect(request.url?.absoluteString == "https://api.example.test/todos?userId=1")
         #expect(request.value(forHTTPHeaderField: "Accept") == "application/json")
         #expect(request.timeoutInterval == 15)
+        #expect(request.cachePolicy == .useProtocolCachePolicy)
     }
 
     @Test(arguments: [404, 500, 503])

The view model tests receive defaults:, because the initializer asks for it now:

NativeTaskManagerTests/TaskListViewModelTests.swift
--- a/NativeTaskManagerTests/TaskListViewModelTests.swift
+++ b/NativeTaskManagerTests/TaskListViewModelTests.swift
@@ -71,7 +71,7 @@
     }
 
     @Test func aFailedReadIsFailed() {
-        let viewModel = TaskListViewModel(repository: FailingTaskRepository(), apiClient: FixtureTodoAPIClient())
+        let viewModel = TaskListViewModel(repository: FailingTaskRepository(), apiClient: FixtureTodoAPIClient(), defaults: .ephemeralSuite())
 
         viewModel.load()
 
@@ -80,7 +80,7 @@
 
     @Test func aFailedChangeKeepsTheListAndReportsIt() {
         let repository = FailingTaskRepository(failsReads: false)
-        let viewModel = TaskListViewModel(repository: repository, apiClient: FixtureTodoAPIClient())
+        let viewModel = TaskListViewModel(repository: repository, apiClient: FixtureTodoAPIClient(), defaults: .ephemeralSuite())
 
         viewModel.add(TaskDraft(title: "a"))
 

And the template's two UI tests launch the app with -ui-testing, so they don't go out to the network:

NativeTaskManagerUITests/NativeTaskManagerUITests.swift
--- a/NativeTaskManagerUITests/NativeTaskManagerUITests.swift
+++ b/NativeTaskManagerUITests/NativeTaskManagerUITests.swift
@@ -19,6 +19,7 @@
     func testExample() throws {
         // UI tests must launch the application that they test.
         let app = XCUIApplication()
+        app.launchArguments = ["-ui-testing"] // in-memory store and fixture API: no network
         app.launch()
 
         // Use XCTAssert and related functions to verify your tests produce the correct results.
@@ -30,7 +31,9 @@
     func testLaunchPerformance() throws {
         // This measures how long it takes to launch your application.
         measure(metrics: [XCTApplicationLaunchMetric()]) {
-            XCUIApplication().launch()
+            let app = XCUIApplication()
+            app.launchArguments = ["-ui-testing"]
+            app.launch()
         }
     }
 }

Try it yourself: delete the app from the simulator to start from scratch, connect the Mac to the internet, and launch it with ⌘R: without touching anything, you see "Importing sample tasks…" and the 20 tasks arrive. Stop the app (⌘.), disconnect the Mac, and launch it again: the 20 tasks are still there, without any error, because nothing was requested.

To use the app without a network and with fixed data, add the argument: Product › Scheme › Edit Scheme… (⌘<), Run in the left column, Arguments tab, and under Arguments Passed On Launch, "+" and -ui-testing. With it, every launch starts with an empty in-memory store and the fixture's three todos are imported. ⌘U has to count 61 tests.

The list in the simulator with the three tasks imported from the fixture, delectus aut autem, quis ut nam facilis et officia qui, and et porro tempora; the last one is completed, with its circle checked and its title struck through.
The first launch imports on its own; with -ui-testing, the fixture's three todos.

The usual mistake: having a test touch the network without anything failing. With the automatic import, the first run of this step on my disposable simulator used the real app as the test host, so it may have asked JSONPlaceholder for data. No test failed: I found it by reading the code, before saving the step. If an app does something at launch, its tests do it too.

Check what you learned. Why isn't the "already imported" flag written before asking for the data?

Solution

Because if the import fails, the flag would say there are already samples and the app would never try again on its own. Written after the success, a first launch without a network is retried on the next one.

What to take away: the network seeds, the local store rules; and the tests must never inherit what the app does at launch.

Download the code for step 09.

Step 10: Filter, Search, Edit, and Delete

What does a list need to be useful with twenty tasks? Being able to find them, fix them, and remove them. This step gives the list the four actions it's missing.

Filtering and Searching as a Pure Function

NativeTaskManager/Features/TaskList/TaskListViewModel.swift
--- a/NativeTaskManager/Features/TaskList/TaskListViewModel.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListViewModel.swift
@@ -18,6 +18,14 @@
 
         var id: Self { self }
 
+        var title: String {
+            switch self {
+            case .all: "All"
+            case .active: "Active"
+            case .completed: "Completed"
+            }
+        }
+
         func includes(_ task: TaskItem) -> Bool {
             switch self {
             case .all: true
@@ -30,6 +38,7 @@
     private(set) var state: LoadState = .idle
     private(set) var tasks: [TaskItem] = []
     var filter: Filter = .all
+    var searchText = ""
     /// A failed change or import while tasks are on screen. The list stays; the view shows an alert.
     var errorMessage: String?
     private(set) var isImporting = false
@@ -42,9 +51,19 @@
     private var importTask: Task<Void, Never>?
 
     var visibleTasks: [TaskItem] {
-        tasks.filter(filter.includes)
+        Self.visibleTasks(in: tasks, filter: filter, searchText: searchText)
     }
 
+    /// Filter and search as a pure function: the view model's state goes in, the rows come out.
+    /// `localizedStandardContains` is what Finder uses: it ignores case and diacritics, so
+    /// "cafe" finds "Café".
+    static func visibleTasks(in tasks: [TaskItem], filter: Filter, searchText: String) -> [TaskItem] {
+        let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
+        return tasks.filter { task in
+            filter.includes(task) && (query.isEmpty || task.title.localizedStandardContains(query))
+        }
+    }
+
     private let repository: any TaskRepository
     private let apiClient: any TodoAPIClient
     private let defaults: UserDefaults
@@ -96,6 +115,16 @@
         perform { try repository.delete(task) }
     }
 
+    /// Runs a change, then re-reads the store so `tasks` always mirrors what is persisted.
+    private func perform(_ change: () throws -> Void) {
+        do {
+            try change()
+        } catch {
+            errorMessage = "The change could not be saved."
+        }
+        load()
+    }
+
     /// Downloads the sample todos and stores the ones not imported yet.
     ///
     /// With an empty list the whole screen shows the progress and, on failure, an error with a
@@ -158,14 +187,4 @@
             return startImport()
         }
     }
-
-    /// Runs a change, then re-reads the store so `tasks` always mirrors what is persisted.
-    private func perform(_ change: () throws -> Void) {
-        do {
-            try change()
-        } catch {
-            errorMessage = "The change could not be saved."
-        }
-        load()
-    }
 }

visibleTasks(in:filter:searchText:) is a static function that receives the tasks, the filter, and the text, and returns the rows. It touches nothing else, so you test it with an array and without a view model. The search trims the spaces and uses localizedStandardContains, Foundation's method for user-facing searches: it ignores case and accents, so "cafe" finds "Café". Filter.title gives the picker's text.

The filter works in memory on what was already read, not with a #Predicate in the query: with dozens of tasks it's instant and you test it as a pure function. With thousands, you'd move it to the FetchDescriptor.

The diff also moves perform(_:) next to the other intents, and in AppDependencies.swift forCurrentProcess() moves to an extension after the class. Neither of the two changes the behavior:

NativeTaskManager/App/AppDependencies.swift
--- a/NativeTaskManager/App/AppDependencies.swift
+++ b/NativeTaskManager/App/AppDependencies.swift
@@ -54,6 +54,12 @@
         }
     }
 
+    func makeTaskListViewModel() -> TaskListViewModel {
+        TaskListViewModel(repository: repository, apiClient: apiClient, defaults: defaults)
+    }
+}
+
+extension AppDependencies {
     /// The dependencies for this process. Tests never reach the network or the real store:
     /// UI tests launch the app with `-ui-testing`, and unit tests run inside the app, which
     /// XCTest marks with `XCTestConfigurationFilePath` in the environment.
@@ -62,8 +68,4 @@
         let isHostingUnitTests = process.environment["XCTestConfigurationFilePath"] != nil
         return isUITesting || isHostingUnitTests ? .inMemory() : .live()
     }
-
-    func makeTaskListViewModel() -> TaskListViewModel {
-        TaskListViewModel(repository: repository, apiClient: apiClient, defaults: defaults)
-    }
 }

The List

NativeTaskManager/Features/TaskList/TaskListView.swift
--- a/NativeTaskManager/Features/TaskList/TaskListView.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListView.swift
@@ -4,6 +4,8 @@
 struct TaskListView: View {
     @Bindable var viewModel: TaskListViewModel
     @State private var isCreating = false
+    @State private var editing: TaskItem?
+    @State private var pendingDeletion: TaskItem?
 
     var body: some View {
         NavigationStack {
@@ -22,6 +24,24 @@
                         viewModel.add(draft)
                     }
                 }
+                .sheet(item: $editing) { task in
+                    TaskFormView(draft: TaskDraft(task: task), isCreating: false) { draft in
+                        viewModel.update(task, with: draft)
+                    }
+                }
+                .confirmationDialog(
+                    "Delete this task?",
+                    isPresented: Binding(
+                        get: { pendingDeletion != nil },
+                        set: { if !$0 { pendingDeletion = nil } }
+                    ),
+                    titleVisibility: .visible,
+                    presenting: pendingDeletion
+                ) { task in
+                    Button("Delete", role: .destructive) { viewModel.delete(task) }
+                } message: { task in
+                    Text("“\(task.title)” will be removed from this device.")
+                }
                 .alert(
                     "Something Went Wrong",
                     isPresented: Binding(
@@ -61,12 +81,58 @@
                     .buttonStyle(.borderedProminent)
             }
         case .loaded:
-            List(viewModel.visibleTasks) { task in
-                TaskRowView(task: task, onToggle: { viewModel.toggleCompletion(of: task) })
+            loadedList
+        }
+    }
+
+    private var loadedList: some View {
+        List {
+            ForEach(viewModel.visibleTasks) { task in
+                TaskRowView(
+                    task: task,
+                    onToggle: { viewModel.toggleCompletion(of: task) },
+                    onEdit: { editing = task }
+                )
+                .swipeActions(allowsFullSwipe: false) {
+                    // No `role: .destructive` here: that role makes the List animate the row away
+                    // at once, before the user confirms. The confirmation dialog deletes.
+                    Button("Delete", systemImage: "trash") { pendingDeletion = task }
+                        .tint(.red)
+                }
             }
         }
+        .overlay {
+            if viewModel.visibleTasks.isEmpty {
+                noMatches
+            }
+        }
+        .safeAreaInset(edge: .top) {
+            Picker("Show", selection: $viewModel.filter) {
+                ForEach(TaskListViewModel.Filter.allCases) { filter in
+                    Text(filter.title).tag(filter)
+                }
+            }
+            .pickerStyle(.segmented)
+            .padding(.horizontal)
+            .padding(.bottom, 8)
+            .background(.bar)
+        }
+        .searchable(text: $viewModel.searchText, prompt: "Search titles")
     }
 
+    @ViewBuilder
+    private var noMatches: some View {
+        if !viewModel.searchText.trimmingCharacters(in: .whitespaces).isEmpty {
+            ContentUnavailableView.search(text: viewModel.searchText)
+        } else {
+            ContentUnavailableView(
+                viewModel.filter == .completed ? "No Completed Tasks" : "No Active Tasks",
+                systemImage: "line.3.horizontal.decrease.circle",
+                description: Text("Change the filter to see the other tasks.")
+            )
+        }
+    }
+
     private var importButton: some View {
         Button(
             viewModel.hasImportedSamples ? "Reimport Sample Tasks" : "Import Sample Tasks",
  • The picker. A segmented Picker (All, Active, Completed) bound to $viewModel.filter, possible because the view receives the view model with @Bindable. It goes in .safeAreaInset(edge: .top): it stays fixed above the list, on .bar, the bar's material: a translucent background that lets you see, blurred, what passes behind it.
  • The search field. .searchable(text:prompt:) adds a search field, bound to $viewModel.searchText. In iOS 27, on an iPhone, it appears at the bottom of the screen, as in this step's screenshot.
  • When nothing is left. If the search finds nothing, ContentUnavailableView.search(text:) says so with the searched text; if it's the filter that leaves the list empty, "No Completed Tasks" or "No Active Tasks". They go as an .overlay on the list, so the picker and the search field stay within reach.
  • Deleting. Swiping the row to the left shows "Delete" (.swipeActions). That button doesn't delete: it stores the task in pendingDeletion, and a .confirmationDialog asks "Delete this task?". The dialog's button deletes, with role: .destructive. allowsFullSwipe: false prevents deleting in a single swipe.
  • Editing. Tapping the row stores the task in editing, and .sheet(item: $editing) opens the same form from step 05 in edit mode, with TaskDraft(task:). On save, update(_:with:) applies the draft and keeps the identity, the completed state, and the remoteID.

The swipe button is painted red with .tint(.red) and carries the trash icon, but it doesn't carry role: .destructive: the reason is below, in the usual mistake.

The Row, With Two Buttons

NativeTaskManager/Features/TaskList/TaskRowView.swift
import SwiftUI
 
/// One task in the list: a completion button and, as a second button, the title and due date,
/// which opens the task for editing.
struct TaskRowView: View {
    let task: TaskItem
    let onToggle: () -> Void
    let onEdit: () -> Void
 
    var body: some View {
        HStack(alignment: .firstTextBaseline, spacing: 12) {
            Button(action: onToggle) {
                // Shape, not only color, tells completed from pending.
                Image(systemName: task.isCompleted ? "checkmark.circle.fill" : "circle")
                    .imageScale(.large)
                    .frame(minWidth: 44, minHeight: 44)
                    .contentShape(Rectangle())
            }
            .buttonStyle(.borderless)
            .accessibilityLabel(task.isCompleted ? "Mark as not completed" : "Mark as completed")
            .accessibilityValue(task.title)
 
            Button(action: onEdit) {
                VStack(alignment: .leading, spacing: 4) {
                    Text(task.title)
                        .strikethrough(task.isCompleted)
                        .foregroundStyle(task.isCompleted ? .secondary : .primary)
                    if let dueDate = task.dueDate {
                        Text("Due \(dueDate, format: .dateTime.day().month().year())")
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }
                }
                .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)
                .contentShape(Rectangle())
            }
            .buttonStyle(.plain)
            .accessibilityValue(task.isCompleted ? "Completed" : "Not completed")
            .accessibilityHint("Opens the task for editing")
        }
    }
}
 
#Preview {
    List(TaskItem.samples()) { task in
        TaskRowView(task: task, onToggle: { task.isCompleted.toggle() }, onEdit: {})
    }
}

The row now has two actions: complete and edit. The title and the date are the second button, with .plain so it looks like text and with accessibilityHint ("Opens the task for editing"), which VoiceOver reads after the name.

The .accessibilityElement(children: .combine) from step 04, which joins the children into a single element, goes away: with two different actions in the row, each one has to be its own element. In exchange, the complete button carries its task's title in accessibilityValue, so VoiceOver says which task it marks.

Going deeper

the tests for this step. A new file with two suites:

NativeTaskManagerTests/TaskFilteringTests.swift
import Foundation
import Testing
@testable import NativeTaskManager
 
@MainActor
struct TaskFilteringTests {
    private let tasks = [
        TaskItem(title: "Buy coffee at the Café"),
        TaskItem(title: "Pay rent", isCompleted: true),
        TaskItem(title: "Call the bank", isCompleted: true),
        TaskItem(title: "Book flights"),
    ]
 
    private func titles(_ filter: TaskListViewModel.Filter, _ search: String = "") -> [String] {
        TaskListViewModel.visibleTasks(in: tasks, filter: filter, searchText: search).map(\.title)
    }
 
    @Test func allShowsEverythingInOrder() {
        #expect(titles(.all) == tasks.map(\.title))
    }
 
    @Test func activeShowsOnlyPendingTasks() {
        #expect(titles(.active) == ["Buy coffee at the Café", "Book flights"])
    }
 
    @Test func completedShowsOnlyDoneTasks() {
        #expect(titles(.completed) == ["Pay rent", "Call the bank"])
    }
 
    @Test(arguments: ["cafe", "CAFÉ", "  coffee  "])
    func searchIgnoresCaseDiacriticsAndSpaces(query: String) {
        #expect(titles(.all, query) == ["Buy coffee at the Café"])
    }
 
    @Test func searchAndFilterCombine() {
        #expect(titles(.completed, "ba") == ["Call the bank"])
        #expect(titles(.active, "ba").isEmpty)
    }
 
    @Test func aBlankSearchMatchesEverything() {
        #expect(titles(.all, "   ").count == tasks.count)
    }
 
    @Test func aSearchWithoutMatchesIsEmpty() {
        #expect(titles(.all, "dentist").isEmpty)
    }
 
    @Test func theViewModelAppliesItsFilterAndSearch() {
        let viewModel = AppDependencies.inMemory(tasks: tasks).makeTaskListViewModel()
        viewModel.load()
 
        viewModel.filter = .active
        viewModel.searchText = "book"
 
        #expect(viewModel.visibleTasks.map(\.title) == ["Book flights"])
    }
}
 
@MainActor
struct TaskDeletionTests {
    @Test func deletingOneTaskKeepsTheOthers() throws {
        let dependencies = AppDependencies.inMemory(tasks: [
            TaskItem(title: "keep", createdAt: Date(timeIntervalSince1970: 1)),
            TaskItem(title: "remove", createdAt: Date(timeIntervalSince1970: 2)),
        ])
        let viewModel = dependencies.makeTaskListViewModel()
        viewModel.load()
 
        viewModel.delete(try #require(viewModel.tasks.first { $0.title == "remove" }))
 
        #expect(viewModel.tasks.map(\.title) == ["keep"])
        #expect(try dependencies.repository.fetchAll().map(\.title) == ["keep"])
        #expect(viewModel.state == .loaded)
    }
 
    @Test func aDeletedTaskLeavesTheFilteredList() throws {
        let viewModel = AppDependencies.inMemory(tasks: [
            TaskItem(title: "done", isCompleted: true),
            TaskItem(title: "open"),
        ]).makeTaskListViewModel()
        viewModel.load()
        viewModel.filter = .completed
 
        viewModel.delete(try #require(viewModel.visibleTasks.first))
 
        #expect(viewModel.visibleTasks.isEmpty)
        #expect(viewModel.tasks.map(\.title) == ["open"])
    }
 
    @Test func editingKeepsTheTaskIdentityAndCompletion() throws {
        let dependencies = AppDependencies.inMemory(tasks: [TaskItem(title: "draft", isCompleted: true, remoteID: 9)])
        let viewModel = dependencies.makeTaskListViewModel()
        viewModel.load()
        let task = try #require(viewModel.tasks.first)
        let id = task.id
 
        viewModel.update(task, with: TaskDraft(title: " final ", notes: "", dueDate: nil))
 
        let stored = try #require(try dependencies.repository.fetchAll().first)
        #expect(stored.id == id)
        #expect(stored.title == "final")
        #expect(stored.isCompleted)
        #expect(stored.remoteID == 9)
    }
}

TaskFilteringTests tests the pure function (all, active, completed; "cafe", "CAFÉ", and " coffee " with case, accents, and spaces; filter and search combined; blank search; no matches) and the view model applying them. TaskDeletionTests tests that deleting a task leaves the others in memory and in the store, that a deleted task leaves the filtered list, and that editing keeps the identity.

Try it yourself: ⌘R with -ui-testing. Tap "Completed" in the picker: "et porro tempora" is left. Tap "Active", search for "facilis", and a single task is left. Tap a row, change the title, and save. Swipe a row to the left, tap "Delete", and confirm in the dialog. When you want to go back to your real data, uncheck -ui-testing in the scheme. ⌘U has to count 72 tests.

The list with the picker on Completed: a single task, et porro tempora, with its circle checked and its title struck through, and the Search titles field at the bottom. At the top, where the title Tasks goes, there's only a blurry gray smudge.
The Completed filter leaves only the finished tasks. The gray smudge at the top is the Tasks title, blurred: it's a bug in this step, and step 12 fixes it.

The usual mistake: putting role: .destructive on the swipe button, because it deletes. With that role, the List animates the row out right away, before the user confirms: the dialog asks about a row that's no longer visible. The role goes on the dialog's button, which is the one that deletes.

Going deeper

a run that times out without anything wrong in the code. This step passed its 72 tests on my simulator, but the verification script cut two runs short with xcodebuild superó 1800s ("xcodebuild exceeded 1800s"). The Mac had its lid closed and no power, and it went to sleep again and again (pmset -g log: Entering Sleep state due to 'Maintenance Sleep').

The limit is measured with the wall clock, which keeps running while the Mac sleeps. In the UI test's log, 420 seconds went by between launching the app and it being ready: one sleep cycle. With the lid open and the Mac plugged in, the same code passed in 2 minutes and 4 seconds. If a run times out with the processor almost idle, look at the power log before the code.

Check what you learned. Why is visibleTasks computed every time and not stored in a property?

Solution

Because it's derived from three pieces of data that are already stored (the tasks, the filter, and the text). Storing the result too would force you to update it every time any of the three changes, and one slip would leave the screen showing a stale list.

What to take away: what's derived is computed; and a destructive action is confirmed before it's animated.

Download the code for step 10.

Note: a good point for a break: you've done 10 of the 12 steps, about four and a half hours. The app already does everything it promises; the two remaining steps test it end to end and review it.

Step 11: UI and Accessibility Tests

How do you know the "Add Task" button still opens the sheet after you've changed a hundred things? With a test that drives the app the way a user does. This step tidies up the unit tests and replaces the template's UI tests with tests that walk through the app and audit it.

The Pyramid in This App

LevelWhat it coversWith whatHow many
UnitMapping, validation, repository, import, view model, first launch, filterSwift Testing, in-memory SwiftData, fake URLProtocol, hand-written doubles69
UICreate, complete, filter, and delete; accessibility audit of the list, in light and darkXCTest and XCUIAutomation, the app with -ui-testing3

The unit tests are many, fast, and precise: when one fails, it says which rule broke. The UI tests are few and slow, and they test that the pieces are connected. It's the pyramid from "Tests: Swift Testing, XCTest, and Test Doubles" applied to a real app.

The Unit Tests, Tidied Up

This step doesn't change any behavior of the unit tests: it reorganizes them. Do it in this order.

1. The support folder. Right-click NativeTaskManagerTests › New Folder › Support.

2. Move the fake protocol and the JSON. Right-click NativeTaskManagerTests › Show in Finder. In Finder, move StubURLProtocol.swift and Fixtures/todos-user1.json to Support/, and delete the Fixtures folder, which is left empty. Xcode reflects it on its own, because the folder is synchronized. The moved file changes a comment:

NativeTaskManagerTests/Support/StubURLProtocol.swift
import Foundation
import Synchronization
import Testing
 
/// Answers every request of a session built with `makeSession()` with a canned stub, so the API
/// client is tested end to end (URLSession, status codes, decoding) without the network.
final class StubURLProtocol: URLProtocol {
    enum Stub: Sendable {
        case response(status: Int, body: Data)
        case failure(URLError.Code)
    }
 
    private struct State: Sendable {
        var stub: Stub?
        var lastRequest: URLRequest?
    }
 
    private static let state = Mutex(State())
 
    static func stub(_ stub: Stub) {
        state.withLock { $0 = State(stub: stub) }
    }
 
    static var lastRequest: URLRequest? {
        state.withLock { $0.lastRequest }
    }
 
    static func makeSession() -> URLSession {
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [StubURLProtocol.self]
        return URLSession(configuration: configuration)
    }
 
    override class func canInit(with request: URLRequest) -> Bool { true }
    override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
 
    override func startLoading() {
        let request = self.request
        let stub = Self.state.withLock { state in
            state.lastRequest = request
            return state.stub
        }
        switch stub {
        case .response(let status, let body):
            let response = HTTPURLResponse(
                url: request.url!, statusCode: status, httpVersion: "HTTP/1.1",
                headerFields: ["Content-Type": "application/json"]
            )!
            client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
            client?.urlProtocol(self, didLoad: body)
            client?.urlProtocolDidFinishLoading(self)
        case .failure(let code):
            client?.urlProtocol(self, didFailWithError: URLError(code))
        case nil:
            client?.urlProtocol(self, didFailWithError: URLError(.resourceUnavailable))
        }
    }
 
    override func stopLoading() {}
}
 
enum Fixture {
    private final class BundleToken {}
 
    /// A JSON file copied into the test bundle (Support/ is inside the synchronized test folder).
    static func data(_ name: String) throws -> Data {
        let url = try #require(Bundle(for: BundleToken.self).url(forResource: name, withExtension: "json"))
        return try Data(contentsOf: url)
    }
}

The JSON stays the same, in its new place:

NativeTaskManagerTests/Support/todos-user1.json
[
  { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false },
  { "userId": 1, "id": 2, "title": "quis ut nam facilis et officia qui", "completed": false },
  { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false },
  { "userId": 1, "id": 4, "title": "et porro tempora", "completed": true }
]

3. The doubles, in a single file. Create Support/TestDoubles.swift:

NativeTaskManagerTests/Support/TestDoubles.swift
import Foundation
@testable import NativeTaskManager
 
// The hand-written test doubles, in one place. No mocking framework: each one is a few lines and
// does exactly what the tests that use it need.
 
/// Answers with scripted results, in order. Before answering it runs `whileFetching` on the main
/// actor, so a test can look at the view model in the middle of an import.
actor ScriptedTodoAPIClient: TodoAPIClient {
    private var results: [Result<[RemoteTodo], APIError>]
    private let whileFetching: @MainActor @Sendable () -> Void
    private(set) var calls = 0
 
    init(_ results: [Result<[RemoteTodo], APIError>], whileFetching: @escaping @MainActor @Sendable () -> Void = {}) {
        self.results = results
        self.whileFetching = whileFetching
    }
 
    func fetchTodos() async throws -> [RemoteTodo] {
        calls += 1
        await whileFetching()
        return try results.removeFirst().get()
    }
}
 
/// Never answers on its own: it waits until its task is cancelled.
struct HangingTodoAPIClient: TodoAPIClient {
    func fetchTodos() async throws -> [RemoteTodo] {
        try await Task.sleep(for: .seconds(60))
        return []
    }
}
 
@MainActor
final class StateProbe {
    var viewModel: TaskListViewModel?
    var seen: [TaskListViewModel.LoadState] = []
}
 
/// A repository whose writes always fail, and whose reads fail unless told otherwise.
@MainActor
final class FailingTaskRepository: TaskRepository {
    struct Failure: Error {}
    private let failsReads: Bool
 
    init(failsReads: Bool = true) {
        self.failsReads = failsReads
    }
 
    func fetchAll() throws -> [TaskItem] {
        if failsReads { throw Failure() }
        return []
    }
 
    func add(_ task: TaskItem) throws { throw Failure() }
    func delete(_ task: TaskItem) throws { throw Failure() }
    func save() throws { throw Failure() }
    func importTodos(_ todos: [RemoteTodo]) throws -> Int { throw Failure() }
}
 
extension UserDefaults {
    /// A suite of its own for one test: tests run in parallel and must not share flags.
    static func ephemeralSuite() -> UserDefaults {
        UserDefaults(suiteName: "tests-\(UUID().uuidString)")!
    }
}

4. Remove the doubles from where they were, or the compiler complains about repeated declarations (invalid redeclaration of 'ScriptedTodoAPIClient'):

NativeTaskManagerTests/ImportStateTests.swift
--- a/NativeTaskManagerTests/ImportStateTests.swift
+++ b/NativeTaskManagerTests/ImportStateTests.swift
@@ -2,40 +2,7 @@
 import Testing
 @testable import NativeTaskManager
 
-/// Answers with scripted results, in order. Before answering it runs `whileFetching` on the main
-/// actor, so a test can look at the view model in the middle of an import.
-actor ScriptedTodoAPIClient: TodoAPIClient {
-    private var results: [Result<[RemoteTodo], APIError>]
-    private let whileFetching: @MainActor @Sendable () -> Void
-    private(set) var calls = 0
-
-    init(_ results: [Result<[RemoteTodo], APIError>], whileFetching: @escaping @MainActor @Sendable () -> Void = {}) {
-        self.results = results
-        self.whileFetching = whileFetching
-    }
-
-    func fetchTodos() async throws -> [RemoteTodo] {
-        calls += 1
-        await whileFetching()
-        return try results.removeFirst().get()
-    }
-}
-
-/// Never answers on its own: it waits until its task is cancelled.
-struct HangingTodoAPIClient: TodoAPIClient {
-    func fetchTodos() async throws -> [RemoteTodo] {
-        try await Task.sleep(for: .seconds(60))
-        return []
-    }
-}
-
 @MainActor
-final class StateProbe {
-    var viewModel: TaskListViewModel?
-    var seen: [TaskListViewModel.LoadState] = []
-}
-
-@MainActor
 struct ImportStateTests {
     private let todos = [RemoteTodo(userId: 1, id: 1, title: "first", completed: false)]
 
NativeTaskManagerTests/FirstLaunchImportTests.swift
--- a/NativeTaskManagerTests/FirstLaunchImportTests.swift
+++ b/NativeTaskManagerTests/FirstLaunchImportTests.swift
@@ -2,13 +2,6 @@
 import Testing
 @testable import NativeTaskManager
 
-extension UserDefaults {
-    /// A suite of its own for one test: tests run in parallel and must not share flags.
-    static func ephemeralSuite() -> UserDefaults {
-        UserDefaults(suiteName: "tests-\(UUID().uuidString)")!
-    }
-}
-
 @MainActor
 struct FirstLaunchImportTests {
     private let todos = [
@@ -90,11 +83,3 @@
         #expect(Set(viewModel.tasks.compactMap(\.remoteID)) == [1, 2])
     }
 }
-
-@MainActor
-struct ProcessDependenciesTests {
-    @Test func theUnitTestHostNeverUsesTheLiveClient() {
-        // These tests run inside the app; its launch must not have reached the network.
-        #expect(AppDependencies.forCurrentProcess().apiClient is FixtureTodoAPIClient)
-    }
-}

TaskListViewModelTests.swift also loses filterSelectsByCompletion: the filtering tests from step 10 cover the same and more. That's why the unit test total goes down by one.

NativeTaskManagerTests/TaskListViewModelTests.swift
--- a/NativeTaskManagerTests/TaskListViewModelTests.swift
+++ b/NativeTaskManagerTests/TaskListViewModelTests.swift
@@ -87,38 +87,4 @@
         #expect(viewModel.errorMessage == "The change could not be saved.")
         #expect(viewModel.state == .empty)
     }
-
-    @Test func filterSelectsByCompletion() {
-        let done = TaskItem(title: "done", isCompleted: true)
-        let open = TaskItem(title: "open")
-        let viewModel = AppDependencies.inMemory(tasks: [done, open]).makeTaskListViewModel()
-        viewModel.load()
-
-        viewModel.filter = .completed
-        #expect(viewModel.visibleTasks.map(\.title) == ["done"])
-
-        viewModel.filter = .active
-        #expect(viewModel.visibleTasks.map(\.title) == ["open"])
-    }
 }
-
-/// A repository whose writes always fail, and whose reads fail unless told otherwise.
-@MainActor
-final class FailingTaskRepository: TaskRepository {
-    struct Failure: Error {}
-    private let failsReads: Bool
-
-    init(failsReads: Bool = true) {
-        self.failsReads = failsReads
-    }
-
-    func fetchAll() throws -> [TaskItem] {
-        if failsReads { throw Failure() }
-        return []
-    }
-
-    func add(_ task: TaskItem) throws { throw Failure() }
-    func delete(_ task: TaskItem) throws { throw Failure() }
-    func save() throws { throw Failure() }
-    func importTodos(_ todos: [RemoteTodo]) throws -> Int { throw Failure() }
-}

5. The host test, in its own file. Create AppDependenciesTests.swift in NativeTaskManagerTests/:

NativeTaskManagerTests/AppDependenciesTests.swift
import Foundation
import Testing
@testable import NativeTaskManager
 
@MainActor
struct ProcessDependenciesTests {
    @Test func theUnitTestHostNeverUsesTheLiveClient() {
        // These tests run inside the app; its launch must not have reached the network.
        #expect(AppDependencies.forCurrentProcess().apiClient is FixtureTodoAPIClient)
    }
}

There's no mocking framework: each double is a few lines and does exactly what its tests need. ScriptedTodoAPIClient is an actor, and an actor's async method satisfies the async requirement of the nonisolated protocol. StateProbe is a main-actor class and that's why it's Sendable: it can be captured in the @MainActor @Sendable closure the client runs.

The UI Tests

Replace the template's file entirely:

NativeTaskManagerUITests/NativeTaskManagerUITests.swift
import XCTest
 
/// End-to-end smoke tests. The app is launched with `-ui-testing`: an in-memory store and the
/// fixture API client, so every run starts empty, imports the same three todos and never
/// touches the network.
final class NativeTaskManagerUITests: XCTestCase {
    override func setUpWithError() throws {
        continueAfterFailure = false
    }
 
    @MainActor
    private func launchApp() -> XCUIApplication {
        let app = XCUIApplication()
        app.launchArguments = ["-ui-testing"]
        app.launch()
        // The first launch imports the fixture todos on its own.
        XCTAssertTrue(app.buttons["delectus aut autem"].waitForExistence(timeout: 10))
        return app
    }
 
    /// The completion button of one row, found the way VoiceOver reads it: its label says the
    /// action and its value names the task.
    @MainActor
    private func completionButton(_ label: String, of title: String, in app: XCUIApplication) -> XCUIElement {
        app.buttons.matching(NSPredicate(format: "label == %@ AND value == %@", label, title)).firstMatch
    }
 
    @MainActor
    func testCreateCompleteFilterAndDeleteATask() throws {
        let app = launchApp()
 
        // Create
        app.buttons["Add Task"].tap()
        let titleField = app.textFields["Title"]
        XCTAssertTrue(titleField.waitForExistence(timeout: 10))
        titleField.tap()
        titleField.typeText("Water the plants")
        app.buttons["Save"].tap()
        XCTAssertTrue(titleField.waitForNonExistence(timeout: 10))
        let row = app.buttons["Water the plants"]
        XCTAssertTrue(row.waitForExistence(timeout: 10))
 
        // Complete
        completionButton("Mark as completed", of: "Water the plants", in: app).tap()
        XCTAssertTrue(completionButton("Mark as not completed", of: "Water the plants", in: app).waitForExistence(timeout: 10))
 
        // Filter
        app.buttons["Active"].tap()
        XCTAssertTrue(row.waitForNonExistence(timeout: 10))
        XCTAssertTrue(app.buttons["delectus aut autem"].exists)
        app.buttons["Completed"].tap()
        XCTAssertTrue(row.waitForExistence(timeout: 10))
        XCTAssertFalse(app.buttons["delectus aut autem"].exists)
 
        // Delete: swipe, then confirm
        row.swipeLeft()
        let swipeDelete = app.buttons["Delete"].firstMatch
        XCTAssertTrue(swipeDelete.waitForExistence(timeout: 10))
        swipeDelete.tap()
        let confirm = app.sheets.buttons["Delete"]
        XCTAssertTrue(confirm.waitForExistence(timeout: 10))
        confirm.tap()
        XCTAssertTrue(row.waitForNonExistence(timeout: 10))
    }
 
    @MainActor
    func testTheTaskListPassesTheAccessibilityAudit() throws {
        let app = launchApp()
        addTaskWithDueDate(in: app)
 
        try app.performAccessibilityAudit()
    }
 
    @MainActor
    func testTheTaskListPassesTheAccessibilityAuditInDarkMode() throws {
        XCUIDevice.shared.appearance = .dark
        defer { XCUIDevice.shared.appearance = .light }
        let app = launchApp()
        addTaskWithDueDate(in: app)
 
        try app.performAccessibilityAudit()
    }
 
    /// A task with a due date, so the audit also sees the due-date caption (the fixture todos
    /// have none).
    @MainActor
    private func addTaskWithDueDate(in app: XCUIApplication) {
        app.buttons["Add Task"].tap()
        let titleField = app.textFields["Title"]
        XCTAssertTrue(titleField.waitForExistence(timeout: 10))
        titleField.tap()
        titleField.typeText("Renew the passport")
        app.switches["Due date"].switches.firstMatch.tap()
        app.buttons["Save"].tap()
        // Audit the list, not the sheet halfway through its dismiss animation.
        XCTAssertTrue(titleField.waitForNonExistence(timeout: 10))
        let row = app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Renew the passport")).firstMatch
        XCTAssertTrue(row.waitForExistence(timeout: 10))
        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label BEGINSWITH %@", "Due ")).firstMatch.exists)
    }
}

These are XCTest tests with XCUIAutomation, the framework that drives the app from the outside: XCUIApplication launches it and its queries (app.buttons["Save"]) find elements the way VoiceOver finds them. Swift Testing doesn't drive XCUIApplication, so the interface is still tested with XCTest, in a separate target.

  • launchApp() launches with -ui-testing and waits for "delectus aut autem", the fixture's first todo, to appear: the first-launch import finished, without a network.
  • testCreateCompleteFilterAndDeleteATask walks through the app: it creates "Water the plants", completes it, checks that the Active filter hides it and Completed shows it, swipes it, taps "Delete", confirms in the dialog (app.sheets.buttons["Delete"]), and checks that it's gone.
  • The complete button is looked up the way VoiceOver reads it: its label says the action and its value names the task. The query uses NSPredicate(format:), Foundation's way of writing a condition as text (label == %@ AND value == %@), which XCUIAutomation evaluates on each element. The test uses the same accessible interface as a VoiceOver user, and if that interface breaks, so does the test.
  • The waits are explicit. waitForExistence and waitForNonExistence wait up to 10 seconds for an element to appear or disappear, for example for the sheet to close.

The Accessibility Audit

performAccessibilityAudit() checks the current screen and fails the test if it finds a problem: contrast, small touch areas, unnamed elements, text that doesn't grow with the system font size. No assertion is needed, as you saw in "UI Tests and Accessibility".

In this step it runs on the list, in light mode and in dark mode (XCUIDevice.shared.appearance, which is restored in a defer), with a task that has a due date so it also sees that text. The form and the empty and error states come in step 12.

The first run failed:

error: -[NativeTaskManagerUITests.NativeTaskManagerUITests testTheTaskListPassesTheAccessibilityAudit] : Contrast nearly passed

The message doesn't say which element. performAccessibilityAudit also accepts a closure that receives each issue found; if you use it to print them, you get "Contrast is not high enough for SwiftUI.AccessibilityNode unless font size is larger.", also without the element. I solved it by testing one hypothesis at a time:

  1. The title of a completed task was drawn in .secondary (gray) as well as struck through. When I removed the gray, the audit passed. Completed tasks are still told apart by the strikethrough and the icon.
  2. When I added a task with a date, it failed again: "Due …" in .caption and .secondary. The fix was a Label with the calendar icon, in the primary color: the size and the icon mark the hierarchy, not the gray.
NativeTaskManager/Features/TaskList/TaskRowView.swift
--- a/NativeTaskManager/Features/TaskList/TaskRowView.swift
+++ b/NativeTaskManager/Features/TaskList/TaskRowView.swift
@@ -22,13 +22,15 @@
 
             Button(action: onEdit) {
                 VStack(alignment: .leading, spacing: 4) {
+                    // Done is shown by the strikethrough and the checkmark, not by dimming the
+                    // text: `.secondary` here failed the contrast audit.
                     Text(task.title)
                         .strikethrough(task.isCompleted)
-                        .foregroundStyle(task.isCompleted ? .secondary : .primary)
                     if let dueDate = task.dueDate {
-                        Text("Due \(dueDate, format: .dateTime.day().month().year())")
+                        // Smaller, with an icon, but full contrast: `.secondary` at caption
+                        // size fails the audit as well.
+                        Label("Due \(dueDate, format: .dateTime.day().month().year())", systemImage: "calendar")
                             .font(.caption)
-                            .foregroundStyle(.secondary)
                     }
                 }
                 .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)

Why testLaunchPerformance Went Away

The template's performance test measures the launch with XCTApplicationLaunchMetric, launching the app several times. Without a saved baseline, it can't fail because of a regression: it only measures.

On a new simulator for each run and on a Mac that shares its workload, the number can't be compared from one run to the next, and it was the most expensive test in the suite. The launch is measured on a real device, with Instruments, as in "Debugging and Performance". testExample doesn't stay either: it launched the app and checked nothing.

Try it yourself: ⌘U has to count 72 tests: 69 unit tests and 3 UI tests. While the UI tests run, watch the simulator: the app opens on its own, types "Water the plants", filters, and deletes.

The usual mistake: a UI test that fails once and passes the next time. The first official run of this step ended with a failure without details; the next one passed entirely, but with odd timings (closing the app from the previous test took 155 seconds, with the Mac under load).

I hardened the waits: 10 seconds instead of 5, waiting for the sheet to close before moving on and before the audit, and waiting for the "Delete" button to exist before tapping it. The next run passed. I don't know which of those waits was the one failing; each one waits for something the test took for granted.

Check what you learned. Why does the UI test look up the complete button by its label and its value, and not by an accessibilityIdentifier?

Solution

Because that way it uses the same information as VoiceOver. If someone deletes the button's label, the test fails, and that's good: the app also stopped being usable with VoiceOver. An identifier just for tests would keep finding the button even if accessibility broke.

What to take away: many unit tests that say which rule failed, a few UI tests that test the wiring, and an audit that finds what your eyes don't see.

Download the code for step 11.

Note: a good point for a break: you've done 11 of the 12 steps, about five hours. All that's left is the review that reads the app with fresh eyes.

Step 12: Architecture Review

What does someone who reads your app for the first time find? This step is that reading. It doesn't add features: it fixes what the review found, leaves every screen audited, and writes down what the app is missing for production.

A Rule Written Twice

NativeTaskManager/Features/TaskList/TaskListViewModel.swift
--- a/NativeTaskManager/Features/TaskList/TaskListViewModel.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListViewModel.swift
@@ -54,16 +54,24 @@
         Self.visibleTasks(in: tasks, filter: filter, searchText: searchText)
     }
 
+    var isSearching: Bool {
+        !Self.trimmedQuery(searchText).isEmpty
+    }
+
     /// Filter and search as a pure function: the view model's state goes in, the rows come out.
-    /// `localizedStandardContains` is what Finder uses: it ignores case and diacritics, so
-    /// "cafe" finds "Café".
+    /// `localizedStandardContains` is Foundation's method for user-facing search: it ignores case
+    /// and diacritics, so "cafe" finds "Café".
     static func visibleTasks(in tasks: [TaskItem], filter: Filter, searchText: String) -> [TaskItem] {
-        let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
+        let query = trimmedQuery(searchText)
         return tasks.filter { task in
             filter.includes(task) && (query.isEmpty || task.title.localizedStandardContains(query))
         }
     }
 
+    private static func trimmedQuery(_ searchText: String) -> String {
+        searchText.trimmingCharacters(in: .whitespacesAndNewlines)
+    }
+
     private let repository: any TaskRepository
     private let apiClient: any TodoAPIClient
     private let defaults: UserDefaults

The view decided whether there was a search by trimming the text with .whitespaces, and the view model trimmed it with .whitespacesAndNewlines: the same rule written twice, and already different (a line break counted as a search on one side and not on the other). Now the view model exposes isSearching and both use trimmedQuery(_:).

Two comments change too. The one on visibleTasks said localizedStandardContains "is what Finder uses", something with no backing; now it says what Foundation documents: it's the method for user-facing searches.

The cache one, in TodoAPIClient.swift, said .useProtocolCachePolicy honored the max-age and the ETag, as if a "Reimport" could come from the cache without asking. Now it says what's observed: since JSONPlaceholder also sends Expires: -1 and Pragma: no-cache, each request is revalidated with the ETag and a 304 comes back, not the body. That file's diff, further down, shows it.

The Title That Came Out Blurry

On every launch, the large "Tasks" title came out as a gray smudge under the filter picker. The cause was in one line from step 10: the Picker goes in .safeAreaInset(edge: .top) with .background(.bar), and background(_:ignoresSafeAreaEdges:) uses .all by default. The material extended upward through the safe area, over the zone where iOS 27 draws the large title, and blurred it. With ignoresSafeAreaEdges: [], the material stays only behind the picker:

NativeTaskManager/Features/TaskList/TaskListView.swift
--- a/NativeTaskManager/Features/TaskList/TaskListView.swift
+++ b/NativeTaskManager/Features/TaskList/TaskListView.swift
@@ -64,21 +64,28 @@
         case .loading:
             ProgressView("Importing sample tasks…")
         case .empty:
-            ContentUnavailableView {
-                Label("No Tasks", systemImage: "checklist")
-            } description: {
-                Text("Tap + to add your first task, or import a few samples.")
-            } actions: {
-                importButton
+            ScrollableState {
+                ContentUnavailableView {
+                    Label("No Tasks", systemImage: "checklist")
+                } description: {
+                    Text("Tap + to add your first task, or import a few samples.")
+                } actions: {
+                    importButton
+                        .stateActionStyle()
+                }
             }
         case .failed(let message):
-            ContentUnavailableView {
-                Label("Something Went Wrong", systemImage: "exclamationmark.triangle")
-            } description: {
-                Text(message)
-            } actions: {
-                Button("Try Again") { viewModel.retry() }
-                    .buttonStyle(.borderedProminent)
+            ScrollableState {
+                ContentUnavailableView {
+                    Label("Something Went Wrong", systemImage: "exclamationmark.triangle")
+                } description: {
+                    Text(message)
+                } actions: {
+                    // Not `.borderedProminent`: white on the accent blue failed the contrast
+                    // audit, and a plain text button failed "Hit area is too small".
+                    Button("Try Again") { viewModel.retry() }
+                        .stateActionStyle()
+                }
             }
         case .loaded:
             loadedList
@@ -115,7 +122,9 @@
             .pickerStyle(.segmented)
             .padding(.horizontal)
             .padding(.bottom, 8)
-            .background(.bar)
+            // `ignoresSafeAreaEdges: []`: by default a background extends through the safe area,
+            // and this material then covered the large "Tasks" title and blurred it.
+            .background(.bar, ignoresSafeAreaEdges: [])
         }
         .searchable(text: $viewModel.searchText, prompt: "Search titles")
     }
@@ -122,7 +131,7 @@
 
     @ViewBuilder
     private var noMatches: some View {
-        if !viewModel.searchText.trimmingCharacters(in: .whitespaces).isEmpty {
+        if viewModel.isSearching {
             ContentUnavailableView.search(text: viewModel.searchText)
         } else {
             ContentUnavailableView(
@@ -151,3 +160,29 @@
 #Preview("Empty") {
     TaskListView(viewModel: AppDependencies.inMemory().makeTaskListViewModel())
 }
+
+private extension View {
+    /// The action of an empty or error screen: large enough to hit, and in the primary color so
+    /// its text keeps full contrast in light and dark.
+    func stateActionStyle() -> some View {
+        buttonStyle(.bordered)
+            .controlSize(.large)
+            .tint(.primary)
+    }
+}
+
+/// Centers a full-screen message when it fits and lets it scroll when it does not: with the
+/// largest text sizes an empty or error screen is taller than the display.
+private struct ScrollableState<Content: View>: View {
+    @ViewBuilder let content: Content
+
+    var body: some View {
+        GeometryReader { proxy in
+            ScrollView {
+                content
+                    .frame(maxWidth: .infinity, minHeight: proxy.size.height)
+            }
+            .scrollBounceBehavior(.basedOnSize)
+        }
+    }
+}
Before the fix: the list filtered on Completed, and at the top, where the title Tasks goes, a blurry gray smudge under the bar's buttons.
Before: the picker's material covers the large title and blurs it.
After the fix: Native Task Manager with the title Tasks sharp above the filter picker and the task list.
After: the material stays only behind the picker, and the title is readable.

The same diff brings the changes from the audits, which I describe below: ScrollableState and stateActionStyle() in the empty and error states, and isSearching.

I found it by looking at simulator screenshots, and I isolated it by removing a single line. The regression test, testTheLargeTitleIsVisibleAndSharp, isn't satisfied with the title existing: the blurry title was still in the accessibility tree, so it also measures that its screenshot has near-black pixels.

A Failed Save, Undone

It's the gap I warned you about in step 06. If save() throws an error, the change stays pending in the ModelContext: the next read includes it, and autosave could save it later. The row showed the change as done while the alert said it hadn't been saved.

NativeTaskManager/Data/TaskRepository.swift
--- a/NativeTaskManager/Data/TaskRepository.swift
+++ b/NativeTaskManager/Data/TaskRepository.swift
@@ -18,9 +18,12 @@
     // using the context after the container is gone crashes.
     private let container: ModelContainer
     private var context: ModelContext { container.mainContext }
+    private let saveChanges: (ModelContext) throws -> Void
 
-    init(container: ModelContainer) {
+    /// `save` is a seam for tests that need a save to fail; the app always uses the default.
+    init(container: ModelContainer, save: @escaping (ModelContext) throws -> Void = { try $0.save() }) {
         self.container = container
+        self.saveChanges = save
     }
 
     func fetchAll() throws -> [TaskItem] {
@@ -29,20 +32,34 @@
 
     func add(_ task: TaskItem) throws {
         context.insert(task)
-        try context.save()
+        try commit()
     }
 
     func delete(_ task: TaskItem) throws {
         context.delete(task)
-        try context.save()
+        try commit()
     }
 
     func save() throws {
-        try context.save()
+        try commit()
     }
 }
 
 extension SwiftDataTaskRepository {
+    /// Saves, or puts the context back to what is stored. Without the rollback a failed save
+    /// leaves the change pending in the context: fetches include pending changes and autosave
+    /// may store it later, so the list would show a change the alert says was not saved.
+    private func commit() throws {
+        do {
+            try saveChanges(context)
+        } catch {
+            context.rollback()
+            throw error
+        }
+    }
+}
+
+extension SwiftDataTaskRepository {
     /// Idempotent: a todo whose `remoteID` is already stored is skipped, so importing twice adds
     /// nothing, and a task the user edited keeps the user's version. Imported tasks are local from
     /// now on; nothing is ever sent back to the sample API.
@@ -55,7 +72,7 @@
             known.insert(todo.id) // also guards against a repeated id inside one response
             added += 1
         }
-        try context.save()
+        try commit()
         return added
     }
 }

Every write now goes through commit(), which saves and, if that fails, calls context.rollback(): a rollback discards what's pending and returns the models to their last saved state, and then rethrows the error. To be able to force the failure in a test, the repository receives the save function (save:), with { try $0.save() } by default; the app always uses the default value.

Every Screen, Audited

In step 11 the audit only saw the list. To audit the form and the empty and error states, you had to reach them without a network and without depending on luck. Two new launch arguments solve it, always with the in-memory store and the fixed client:

  • -ui-testing-import-failure: the first-launch import fails as if there were no connection, and the app opens on the error screen.
  • -ui-testing-no-samples: the client returns no todos, and the app opens on the empty state.
NativeTaskManager/App/AppDependencies.swift
--- a/NativeTaskManager/App/AppDependencies.swift
+++ b/NativeTaskManager/App/AppDependencies.swift
@@ -61,9 +61,16 @@
 
 extension AppDependencies {
     /// The dependencies for this process. Tests never reach the network or the real store:
-    /// UI tests launch the app with `-ui-testing`, and unit tests run inside the app, which
-    /// XCTest marks with `XCTestConfigurationFilePath` in the environment.
+    /// UI tests launch the app with `-ui-testing`, and unit tests run inside the app, which XCTest
+    /// marks with `XCTestConfigurationFilePath` in the environment. Two more arguments open the
+    /// screens a working import never shows: the error and the empty list.
     static func forCurrentProcess(_ process: ProcessInfo = .processInfo) -> AppDependencies {
+        if process.arguments.contains("-ui-testing-import-failure") {
+            return .inMemory(apiClient: FixtureTodoAPIClient(failure: .offline))
+        }
+        if process.arguments.contains("-ui-testing-no-samples") {
+            return .inMemory(apiClient: FixtureTodoAPIClient(todos: []))
+        }
         let isUITesting = process.arguments.contains("-ui-testing")
         let isHostingUnitTests = process.environment["XCTestConfigurationFilePath"] != nil
         return isUITesting || isHostingUnitTests ? .inMemory() : .live()
NativeTaskManager/Networking/TodoAPIClient.swift
--- a/NativeTaskManager/Networking/TodoAPIClient.swift
+++ b/NativeTaskManager/Networking/TodoAPIClient.swift
@@ -23,8 +23,9 @@
     func makeRequest() -> URLRequest {
         var components = URLComponents(url: baseURL.appending(path: "todos"), resolvingAgainstBaseURL: false)!
         components.queryItems = [URLQueryItem(name: "userId", value: "1")]
-        // HTTP caching is left to URLCache and the server: JSONPlaceholder answers with
-        // `Cache-Control: max-age=43200` and an ETag, and `.useProtocolCachePolicy` honors both.
+        // HTTP caching is left to URLCache and the server. JSONPlaceholder answers with
+        // `Cache-Control: max-age=43200` and an ETag, but also `Expires: -1` and `Pragma: no-cache`,
+        // so `.useProtocolCachePolicy` revalidates every request with the ETag: a 304, not the body.
         // No cache layer of our own: SwiftData already keeps every imported task offline.
         // The default timeout is 60 s; for a small JSON a user is waiting on, 15 s is plenty.
         var request = URLRequest(url: components.url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: timeout)
@@ -54,7 +55,8 @@
     }
 }
 
-/// A fixed, offline client: previews use it, and UI tests will (never the network).
+/// A fixed, offline client for previews and UI tests (never the network). With a `failure`, every
+/// fetch throws it, so the error screen can be shown on demand.
 nonisolated struct FixtureTodoAPIClient: TodoAPIClient {
     var todos: [RemoteTodo] = [
         RemoteTodo(userId: 1, id: 1, title: "delectus aut autem", completed: false),
@@ -61,8 +63,10 @@
         RemoteTodo(userId: 1, id: 2, title: "quis ut nam facilis et officia qui", completed: false),
         RemoteTodo(userId: 1, id: 4, title: "et porro tempora", completed: true),
     ]
+    var failure: APIError?
 
     func fetchTodos() async throws -> [RemoteTodo] {
-        todos
+        if let failure { throw failure }
+        return todos
     }
 }

The new audits found real problems. Dynamic Type is the font size the user picks in the iPhone's settings; with the largest sizes, a fixed full-screen message doesn't fit and gets clipped.

ScreenWhat the audit saidThe fix
Error: "Try Again" with .borderedProminentContrast nearly passed (white on the accent blue); without that style, Hit area is too smallstateActionStyle(): .bordered, .controlSize(.large), and .tint(.primary)
Error and emptyDynamic Type font sizes are partially unsupported and, in the error, Text clippedScrollableState: centers the message when it fits and lets it scroll when it doesn't
Form: Cancel and SaveContrast failed and Dynamic Type font sizes are partially unsupportedbuttons with icon and text (systemImage: "xmark" and "checkmark")
Form: "Enter a title."Contrast nearly passed (red in .footnote) and Text clippedred icon and text in the primary color, in an HStack that can wrap onto several lines
The finished app's error screen: the title Tasks, a warning icon, Something Went Wrong, the message You seem to be offline. Check your connection and try again., and the Try Again button, gray and large.
The error screen, with -ui-testing-import-failure: the button is no longer blue with white text, and it passes the audit.
The finished app's empty state: the title Tasks, a list icon, No Tasks, the description Tap + to add your first task, or import a few samples., and the Reimport Sample Tasks button.
The empty state, with -ui-testing-no-samples: the import worked but brought no tasks, so the button now says Reimport.

ScrollableState uses two new pieces: GeometryReader, a view that tells its content how much space it has, and .scrollBounceBehavior(.basedOnSize), which makes the ScrollView bounce only when the content doesn't fit. That way the message stays centered and still if it fits, and scrolls if it doesn't. In the sheet's bar buttons, the bar shows the icon, and VoiceOver and the tests still read "Cancel" and "Save".

NativeTaskManager/Features/TaskForm/TaskFormView.swift
--- a/NativeTaskManager/Features/TaskForm/TaskFormView.swift
+++ b/NativeTaskManager/Features/TaskForm/TaskFormView.swift
@@ -52,11 +52,13 @@
             .navigationTitle(isCreating ? "New Task" : "Edit Task")
             .navigationBarTitleDisplayMode(.inline)
             .toolbar {
+                // Icons with text labels: VoiceOver and the UI tests read "Cancel" and "Save".
+                // Text buttons here failed the contrast and Dynamic Type audits.
                 ToolbarItem(placement: .cancellationAction) {
-                    Button("Cancel") { dismiss() }
+                    Button("Cancel", systemImage: "xmark") { dismiss() }
                 }
                 ToolbarItem(placement: .confirmationAction) {
-                    Button("Save") {
+                    Button("Save", systemImage: "checkmark") {
                         onSave(draft.normalized)
                         dismiss()
                     }
@@ -78,14 +80,22 @@
     }
 }
 
-/// An inline validation message: an icon and text, so it does not rely on red alone.
+/// An inline validation message: a red icon and text in the primary color. Red text at
+/// footnote size nearly failed the contrast audit; the icon keeps the warning visible.
+/// An `HStack` and not a `Label`: inside a `Form` row a `Label` takes the row's icon-and-title
+/// layout, and the audit reported the text as clipped.
 private struct FieldError: View {
     let message: String
 
     var body: some View {
-        Label(message, systemImage: "exclamationmark.circle")
-            .font(.footnote)
-            .foregroundStyle(.red)
+        HStack(alignment: .firstTextBaseline, spacing: 6) {
+            Image(systemName: "exclamationmark.circle")
+                .foregroundStyle(.red)
+                .accessibilityHidden(true)
+            Text(message)
+                .fixedSize(horizontal: false, vertical: true)
+        }
+        .font(.footnote)
     }
 }
 
Going deeper

the tests for this step. Six new tests force a failing save and check that the list stays as it's stored: a failed completion change, addition, edit, deletion, and import, and that, after undoing, a save that does work saves only its own change. With rollback() commented out, all six failed.

NativeTaskManagerTests/FailedSaveTests.swift
import Foundation
import SwiftData
import Testing
@testable import NativeTaskManager
 
/// When a save fails, the list must show what is stored, not the change that failed: the
/// repository rolls the context back. A second repository over the same in-memory store makes
/// every save fail.
@MainActor
struct FailedSaveTests {
    struct SaveFailure: Error {}
 
    private let dependencies = AppDependencies.inMemory(tasks: [TaskItem(title: "stored")])
 
    private func viewModelWhoseSavesFail() -> TaskListViewModel {
        let failing = SwiftDataTaskRepository(container: dependencies.modelContainer) { _ in throw SaveFailure() }
        let viewModel = TaskListViewModel(
            repository: failing,
            apiClient: FixtureTodoAPIClient(),
            defaults: .ephemeralSuite()
        )
        viewModel.load()
        return viewModel
    }
 
    @Test func aFailedToggleIsRolledBack() throws {
        let viewModel = viewModelWhoseSavesFail()
 
        viewModel.toggleCompletion(of: try #require(viewModel.tasks.first))
 
        #expect(viewModel.errorMessage == "The change could not be saved.")
        #expect(viewModel.tasks.first?.isCompleted == false)
    }
 
    @Test func aFailedAddLeavesNoTask() {
        let viewModel = viewModelWhoseSavesFail()
 
        viewModel.add(TaskDraft(title: "never saved"))
 
        #expect(viewModel.tasks.map(\.title) == ["stored"])
    }
 
    @Test func aFailedEditIsRolledBack() throws {
        let viewModel = viewModelWhoseSavesFail()
 
        viewModel.update(try #require(viewModel.tasks.first), with: TaskDraft(title: "renamed"))
 
        #expect(viewModel.tasks.map(\.title) == ["stored"])
    }
 
    @Test func aFailedDeleteKeepsTheTask() throws {
        let viewModel = viewModelWhoseSavesFail()
 
        viewModel.delete(try #require(viewModel.tasks.first))
 
        #expect(viewModel.tasks.map(\.title) == ["stored"])
        #expect(viewModel.state == .loaded)
    }
 
    @Test func aFailedImportAddsNothing() async {
        let viewModel = viewModelWhoseSavesFail()
 
        await viewModel.importSamples()
 
        #expect(viewModel.tasks.map(\.title) == ["stored"])
        #expect(viewModel.errorMessage == "The sample tasks could not be saved.")
    }
 
    @Test func afterARollbackAWorkingSaveStillStores() throws {
        // The rollback must leave the context usable, not just clean.
        viewModelWhoseSavesFail().add(TaskDraft(title: "never saved"))
        let working = dependencies.makeTaskListViewModel()
 
        working.add(TaskDraft(title: "saved"))
 
        let other = ModelContext(dependencies.modelContainer)
        #expect(Set(try other.fetch(FetchDescriptor<TaskItem>()).map(\.title)) == ["stored", "saved"])
    }
}

The host test gains a case: what -ui-testing-import-failure launches ends up on the error screen.

NativeTaskManagerTests/AppDependenciesTests.swift
--- a/NativeTaskManagerTests/AppDependenciesTests.swift
+++ b/NativeTaskManagerTests/AppDependenciesTests.swift
@@ -8,4 +8,15 @@
         // These tests run inside the app; its launch must not have reached the network.
         #expect(AppDependencies.forCurrentProcess().apiClient is FixtureTodoAPIClient)
     }
+
+    @Test func theFailingFixtureShowsTheErrorScreen() async {
+        // What `-ui-testing-import-failure` launches: the in-memory store and an import that fails.
+        let viewModel = AppDependencies.inMemory(apiClient: FixtureTodoAPIClient(failure: .offline))
+            .makeTaskListViewModel()
+
+        viewModel.onAppear()
+        await viewModel.startImport().value
+
+        #expect(viewModel.state == .failed(message: APIError.offline.userMessage))
+    }
 }

The search rule, pinned with three arguments:

NativeTaskManagerTests/TaskFilteringTests.swift
--- a/NativeTaskManagerTests/TaskFilteringTests.swift
+++ b/NativeTaskManagerTests/TaskFilteringTests.swift
@@ -45,6 +45,15 @@
         #expect(titles(.all, "dentist").isEmpty)
     }
 
+    @Test(arguments: [("", false), ("  \n", false), (" rent ", true)])
+    func isSearchingIgnoresBlankText(text: String, expected: Bool) {
+        let viewModel = AppDependencies.inMemory().makeTaskListViewModel()
+
+        viewModel.searchText = text
+
+        #expect(viewModel.isSearching == expected)
+    }
+
     @Test func theViewModelAppliesItsFilterAndSearch() {
         let viewModel = AppDependencies.inMemory(tasks: tasks).makeTaskListViewModel()
         viewModel.load()

And the UI tests: the sharp-title one, the error audit in light and dark, the empty one, and the form one, with the inline error visible and the date picker open.

type(_:into:) waits for the field to have keyboard focus before typing: the field exists as soon as the sheet starts coming in, and a tap during the animation may not give it focus (Neither element nor any descendant has keyboard focus). The form audit dismisses the keyboard first: with the keyboard up, it also went through the system keys and ended in Audit failed to complete in time.

NativeTaskManagerUITests/NativeTaskManagerUITests.swift
--- a/NativeTaskManagerUITests/NativeTaskManagerUITests.swift
+++ b/NativeTaskManagerUITests/NativeTaskManagerUITests.swift
@@ -18,6 +18,19 @@
         return app
     }
 
+    /// Types into a field once it really has keyboard focus. The field exists as soon as the
+    /// sheet starts to slide in, and a tap during that animation can leave it unfocused
+    /// ("Neither element nor any descendant has keyboard focus").
+    @MainActor
+    private func type(_ text: String, into field: XCUIElement) {
+        let focused = XCTNSPredicateExpectation(predicate: NSPredicate(format: "hasKeyboardFocus == true"), object: field)
+        field.tap()
+        if XCTWaiter.wait(for: [focused], timeout: 5) != .completed {
+            field.tap()
+        }
+        field.typeText(text)
+    }
+
     /// The completion button of one row, found the way VoiceOver reads it: its label says the
     /// action and its value names the task.
     @MainActor
@@ -33,8 +46,7 @@
         app.buttons["Add Task"].tap()
         let titleField = app.textFields["Title"]
         XCTAssertTrue(titleField.waitForExistence(timeout: 10))
-        titleField.tap()
-        titleField.typeText("Water the plants")
+        type("Water the plants", into: titleField)
         app.buttons["Save"].tap()
         XCTAssertTrue(titleField.waitForNonExistence(timeout: 10))
         let row = app.buttons["Water the plants"]
@@ -63,7 +75,46 @@
         XCTAssertTrue(row.waitForNonExistence(timeout: 10))
     }
 
+    /// Regression test: a material behind the filter picker once covered the large title and
+    /// blurred it. The title stayed in the accessibility tree, so `exists` alone would not have
+    /// failed; its pixels show the difference.
     @MainActor
+    func testTheLargeTitleIsVisibleAndSharp() throws {
+        let app = launchApp()
+
+        let title = app.navigationBars["Tasks"].staticTexts["Tasks"]
+        XCTAssertTrue(title.waitForExistence(timeout: 10))
+        XCTAssertTrue(title.isHittable)
+        // Black text in light mode: its darkest pixels are near 0. Blurred, it stayed mid gray.
+        XCTAssertLessThan(darkestLuminance(of: title), 0.3)
+    }
+
+    /// The darkest pixel of an element's screenshot, from 0 (black) to 1 (white).
+    @MainActor
+    private func darkestLuminance(of element: XCUIElement) -> Double {
+        guard let image = element.screenshot().image.cgImage else { return 1 }
+        let width = image.width
+        let height = image.height
+        var pixels = [UInt8](repeating: 0, count: width * height * 4)
+        let drawn = pixels.withUnsafeMutableBytes { buffer -> Bool in
+            guard let context = CGContext(
+                data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8,
+                bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(),
+                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
+            ) else { return false }
+            context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
+            return true
+        }
+        guard drawn else { return 1 }
+        var darkest = 1.0
+        for i in stride(from: 0, to: pixels.count, by: 4) {
+            let luminance = 0.2126 * Double(pixels[i]) + 0.7152 * Double(pixels[i + 1]) + 0.0722 * Double(pixels[i + 2])
+            darkest = min(darkest, luminance / 255)
+        }
+        return darkest
+    }
+
+    @MainActor
     func testTheTaskListPassesTheAccessibilityAudit() throws {
         let app = launchApp()
         addTaskWithDueDate(in: app)
@@ -81,6 +132,60 @@
         try app.performAccessibilityAudit()
     }
 
+    /// Launches with `-ui-testing-import-failure`: an empty in-memory store whose first import
+    /// fails as if the device were offline, so the app opens on the error screen.
+    @MainActor
+    private func launchIntoImportError() -> XCUIApplication {
+        let app = XCUIApplication()
+        app.launchArguments = ["-ui-testing-import-failure"]
+        app.launch()
+        XCTAssertTrue(app.buttons["Try Again"].waitForExistence(timeout: 10))
+        XCTAssertTrue(app.staticTexts["You seem to be offline. Check your connection and try again."].exists)
+        return app
+    }
+
+    @MainActor
+    func testTheImportErrorPassesTheAccessibilityAudit() throws {
+        let app = launchIntoImportError()
+
+        try app.performAccessibilityAudit()
+    }
+
+    @MainActor
+    func testTheImportErrorPassesTheAccessibilityAuditInDarkMode() throws {
+        XCUIDevice.shared.appearance = .dark
+        defer { XCUIDevice.shared.appearance = .light }
+        let app = launchIntoImportError()
+
+        try app.performAccessibilityAudit()
+    }
+
+    @MainActor
+    func testTheEmptyStatePassesTheAccessibilityAudit() throws {
+        let app = XCUIApplication()
+        app.launchArguments = ["-ui-testing-no-samples"]
+        app.launch()
+        XCTAssertTrue(app.staticTexts["No Tasks"].waitForExistence(timeout: 10))
+
+        try app.performAccessibilityAudit()
+    }
+
+    @MainActor
+    func testTheTaskFormPassesTheAccessibilityAudit() throws {
+        let app = launchApp()
+        app.buttons["Add Task"].tap()
+        let titleField = app.textFields["Title"]
+        XCTAssertTrue(titleField.waitForExistence(timeout: 10))
+        // Show the inline error and the date picker, so the audit sees them too.
+        type("x" + XCUIKeyboardKey.delete.rawValue + "\n", into: titleField)
+        XCTAssertTrue(app.staticTexts["Enter a title."].waitForExistence(timeout: 10))
+        // Return dismissed the keyboard: the audit covers the form, not the system keyboard.
+        XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 10))
+        app.switches["Due date"].switches.firstMatch.tap()
+
+        try app.performAccessibilityAudit()
+    }
+
     /// A task with a due date, so the audit also sees the due-date caption (the fixture todos
     /// have none).
     @MainActor
@@ -88,8 +193,7 @@
         app.buttons["Add Task"].tap()
         let titleField = app.textFields["Title"]
         XCTAssertTrue(titleField.waitForExistence(timeout: 10))
-        titleField.tap()
-        titleField.typeText("Renew the passport")
+        type("Renew the passport", into: titleField)
         app.switches["Due date"].switches.firstMatch.tap()
         app.buttons["Save"].tap()
         // Audit the list, not the sheet halfway through its dismiss animation.
Going deeper

the project's README. The essentials of the app, for whoever opens the zip without having read this guide:

README.md
# Native Task Manager
 
La app de la parte 4 de la serie «Ingeniería iOS nativa»: un gestor de tareas en SwiftUI con
SwiftData, que importa tareas de ejemplo de una API REST y desde ahí las gestiona en local. Sin
dependencias de terceros.
 
## Requisitos
 
- Xcode 27.2 (Swift 6.4.2). El proyecto compila en modo de lenguaje Swift 6, con concurrencia
  estricta.
- Un simulador de iOS 27.2. Las verificaciones se hicieron en un iPhone 17.
- La app apunta a iOS 18.0 o posterior (`IPHONEOS_DEPLOYMENT_TARGET`).
 
## Cómo correrla
 
1. Abre `NativeTaskManager.xcodeproj` en Xcode.
2. Elige el esquema `NativeTaskManager` y un simulador.
3. Run (⌘R).
 
En el primer arranque, la app descarga 20 tareas de ejemplo de
`https://jsonplaceholder.typicode.com/todos?userId=1`. Solo entonces necesita red; después
funciona sin conexión.
 
Para usarla sin red, agrega el argumento `-ui-testing` en *Edit Scheme… → Run → Arguments*. Con
él, la app usa un store en memoria y tres tareas fijas, y cada arranque empieza de cero. Es el mismo
modo que usan las pruebas de UI.
 
## Cómo correr las pruebas
 
En Xcode, Test (⌘U). Desde la terminal:
 
```sh
xcodebuild -project NativeTaskManager.xcodeproj -scheme NativeTaskManager \
  -destination 'platform=iOS Simulator,name=iPhone 17' test
```
 
Ninguna prueba usa la red:
 
- **Pruebas unitarias** (Swift Testing, en `NativeTaskManagerTests/`): el modelo y el mapeo, el
  validador, el repositorio sobre un `ModelContainer` en memoria, el view model, la importación, el
  primer arranque y el filtro. El cliente HTTP se prueba de punta a punta con un `URLProtocol` de
  stub y un JSON fijo (`NativeTaskManagerTests/Support/`).
- **Pruebas de UI** (XCUITest, en `NativeTaskManagerUITests/`): crear, completar, filtrar y borrar
  una tarea, más `performAccessibilityAudit()` en modo claro y oscuro.
 
Las pruebas unitarias corren dentro de la app (es el host de pruebas). La app reconoce ese caso y
el argumento `-ui-testing`, y en ambos usa el store en memoria y el cliente fijo. Lo resuelve
`AppDependencies.forCurrentProcess()`.
 
## Qué hace
 
- Lista las tareas. Cada fila tiene un botón para completarla, que cambia de forma y tacha el
  título (no solo el color), y la fecha límite si la tiene.
- Crea una tarea con + y la edita tocando la fila. El formulario valida en línea: el título no puede
  quedar vacío ni pasar de 80 caracteres, y al crear, la fecha límite no puede ser anterior a hoy.
  Save se deshabilita mientras haya errores.
- Filtra por Todas, Activas o Completadas, y busca por título sin distinguir mayúsculas ni tildes.
- Borra deslizando la fila y confirmando.
- Importa las tareas de ejemplo sola en el primer arranque. *Reimport Sample Tasks*, en el menú de
  la barra, vuelve a pedirlas sin duplicar ninguna.
- Muestra estados de carga, vacío y error. Si la importación falla con la lista vacía, aparece un
  error con *Try Again*. Si ya tienes tareas, la lista se queda y el fallo sale como alerta. La
  importación se cancela si la pantalla desaparece.
 
## El contrato de datos: importar no es sincronizar
 
La API de ejemplo es de solo lectura para la app. JSONPlaceholder acepta escrituras, pero no las
guarda, así que enviarle los cambios solo simularía una sincronización.
 
- **Importar** trae los todos de `/todos?userId=1` y los guarda en SwiftData como tareas
  (`TaskItem`), con su `remoteID`.
- **Después, las tareas son tuyas.** Crear, editar, completar y borrar pasa solo en el store local.
  Nada vuelve a la API.
- **La importación es idempotente por `remoteID`, y lo local gana.** Un todo que ya está se salta,
  aunque lo hayas editado. Reimportar no duplica nada y no pisa tus cambios. Lo único que hace es
  devolver un ejemplo que hayas borrado.
- **La caché la decide el protocolo HTTP.** La petición usa `.useProtocolCachePolicy`, y el
  servidor responde con `Cache-Control: max-age=43200` y un ETag, pero también con `Expires: -1` y
  `Pragma: no-cache`: cada importación se revalida con el ETag y vuelve un 304, sin el cuerpo. No
  hay una capa de caché propia: SwiftData ya guarda todo lo importado.
 
## Estructura
 
| Carpeta                          | Qué hay                                                                  |
| -------------------------------- | ------------------------------------------------------------------------ |
| `NativeTaskManager/App/`         | `AppDependencies`, la raíz de composición: elige store, cliente y ajustes |
| `NativeTaskManager/Models/`      | `TaskItem` (`@Model`), `RemoteTodo` (DTO de la API) y el mapeo           |
| `NativeTaskManager/Data/`        | `TaskRepository` y su implementación sobre SwiftData                     |
| `NativeTaskManager/Networking/`  | `TodoAPIClient`, el cliente con `URLSession` y `APIError`                |
| `NativeTaskManager/Features/`    | Lista (vista, fila, view model) y formulario (vista, validador)          |
| `NativeTaskManagerTests/`        | Pruebas unitarias; dobles de prueba y fixture en `Support/`              |
| `NativeTaskManagerUITests/`      | El flujo de UI y los audits de accesibilidad                              |
 
La arquitectura es MVVM con inyección por inicializadores. `TaskListViewModel` (`@Observable`, en
el MainActor) es dueño del estado y de los cambios. Las vistas solo lo muestran y le pasan las
acciones. No hay contenedor de dependencias ni framework de mocks: con un view model, un `init`
alcanza.
 
## Qué le faltaría para producción
 
Esta app enseña los fundamentos. Una app real agregaría, como mínimo:
 
- **Sincronización.** Un backend propio con escrituras reales, o CloudKit. Implica resolver
  conflictos entre dispositivos, guardar cambios hechos sin conexión y reintentar.
- **Autenticación.** Cuentas, tokens guardados en el llavero y su renovación.
- **Reporte de errores.** Registro con `os.Logger`, métricas y diagnósticos con MetricKit, y un
  servicio de reporte de crashes.
- **Migraciones.** Versionar el esquema (`VersionedSchema` y `SchemaMigrationPlan`) antes de la
  primera versión publicada. Sin eso, cambiar `TaskItem` rompe los stores de quienes ya instalaron
  la app.
- **Paginación.** Esta app pide 20 elementos de una vez. Con datos reales se pagina (por cursor, o
  con `_page` y `_limit` en JSONPlaceholder).
- **Localización.** Los textos de la interfaz están solo en inglés. Un String Catalog los
  traduciría (el proyecto ya tiene `LOCALIZATION_PREFERS_STRING_CATALOGS`).

The Map

Hand-drawn diagram in five rows. At the top, the views TaskListView, TaskRowView and TaskFormView, in Features. Actions go down to TaskListViewModel, @Observable and on the main actor, and state goes back up to the views. The view model depends on two protocols: TaskRepository, in Data, and TodoAPIClient, in Networking. SwiftDataTaskRepository implements TaskRepository and stores in SwiftData, with SQLite on the device: the source of truth. URLSessionTodoAPIClient and FixtureTodoAPIClient implement TodoAPIClient; the first reads JSONPlaceholder /todos?userId=1 one way only, read-only, and the second is for tests and previews, with no network. On the left, AppDependencies, in App, the composition root, with live(), inMemory() and forCurrentProcess(), creates and wires the pieces. At the bottom, Models: TaskItem, the @Model the app stores, and RemoteTodo, the DTO the network sends.
The finished app: the arrow toward JSONPlaceholder goes in one direction only, because the app only reads.
NativeTaskManager/App/AppDependencies.swift
final class AppDependencies {
    let modelContainer: ModelContainer
    let repository: any TaskRepository
    let apiClient: any TodoAPIClient
    let defaults: UserDefaults
 
    init(modelContainer: ModelContainer, apiClient: any TodoAPIClient, defaults: UserDefaults) {
        self.modelContainer = modelContainer
        self.repository = SwiftDataTaskRepository(container: modelContainer)
        self.apiClient = apiClient
        self.defaults = defaults
    }
 
    /// The real app: an on-disk store in the app's container.
    static func live() -> AppDependencies {
        do {
            return AppDependencies(
                modelContainer: try ModelContainer(for: TaskItem.self),
                apiClient: URLSessionTodoAPIClient(),
                defaults: .standard
            )
        } catch {
            // Without its store the app cannot do anything useful; failing loudly beats a blank screen.
            fatalError("Could not open the task store: \(error)")
        }
    }
 
    /// Previews and tests: a store that lives only in memory, optionally pre-filled, an API client
    /// that never touches the network and, unless given, a fresh UserDefaults suite of its own.
    static func inMemory(
        tasks: [TaskItem] = [],
        apiClient: any TodoAPIClient = FixtureTodoAPIClient(),
        defaults: UserDefaults? = nil
    ) -> AppDependencies {
        do {
            let container = try ModelContainer(
                for: TaskItem.self,
                configurations: ModelConfiguration(isStoredInMemoryOnly: true)
            )
            tasks.forEach(container.mainContext.insert)
            try container.mainContext.save()
            return AppDependencies(
                modelContainer: container,
                apiClient: apiClient,
                defaults: defaults ?? UserDefaults(suiteName: "in-memory-\(UUID().uuidString)")!
            )
        } catch {
            fatalError("Could not create the in-memory store: \(error)")
        }
    }
 
    func makeTaskListViewModel() -> TaskListViewModel {
        TaskListViewModel(repository: repository, apiClient: apiClient, defaults: defaults)
    }
}

The composition root is the only place that names concrete types: SwiftDataTaskRepository, URLSessionTodoAPIClient, UserDefaults.standard. The rest of the app receives protocols through its initializers, and that's why each piece is tested with another in its place.

What MVVM is here. The views (TaskListView, TaskRowView, TaskFormView) draw the state and pass each action to the view model. TaskListViewModel owns the screen's state and the rules: what's shown, what happens on failure, when to import. The model is TaskItem.

What there is of Clean here. Little, and on purpose. The Clean rule that is present is the direction of the dependencies: the view model depends on two protocols, not on SwiftData or URLSession.

What's missing are use cases as separate objects, navigation coordinators, or a dependency container: with one screen and one implementation of each protocol, each of them would be a class with no second use and no test that asks for it. It's the criterion from part 2.

What I'd remove. Nothing else. The most debatable abstraction is TaskRepository, with a single implementation, and it stays because FailingTaskRepository uses it in the error tests.

What Is a Simplification

A team review would flag these things, which here are conscious decisions for a practice app:

  • Rereading everything after each change. With thousands of tasks, you'd replace it with an in-place update or an observed query, and the filter would go in the FetchDescriptor.
  • One view model for the whole app. It lives in an @State of the app, so every window shares it: on an iPad with two windows, they'd share the filter, and one window's .onDisappear would cancel the other's import. With several windows, each scene would have its own.
  • The old task that clears the new one. If an import is cancelled and another one starts right away, the old one, when it finishes, sets importTask = nil and can erase the reference to the new one. Today it can't be triggered (the list is the root); a token per import would prevent it.
  • The test modes travel in the published version. forCurrentProcess() honors the test arguments in any build. Wrapping it in #if DEBUG, or using your own variable defined in the scheme's Test action instead of an XCTest one, would leave it in development only.
  • UserDefaults suites that stay behind. Every launch with -ui-testing and every test creates a suite with a unique name that nobody deletes; removePersistentDomain(forName:) at the end would clean them up.
  • The complete button's accessibility value carries the task's title. The more conventional approach is for the label to say the task ("Mark Water the plants as completed") and the value, the state; if you change it, change the UI test's query too.
  • fatalError if the store doesn't open. In production you'd want to log the error and offer a way out, like starting with a new store.

What It's Missing for Production

The README, in the box above, lists six things: sync, authentication, error reporting, migrations, pagination, and localization. What I add here is where each one is taught in the series, and a seventh the README doesn't name:

  • Authentication: the tokens go in the Keychain, as in "The Keychain".
  • Error logging: today each catch turns the error into text and discards it; one line with Logger from the os framework would leave it logged, and MetricKit collects metrics and diagnostics from the device.
  • Localization: the project already comes with LOCALIZATION_PREFERS_STRING_CATALOGS, and a String Catalog, the file of translatable text from "Resources", would translate them.
  • A privacy manifest, the missing one: the app uses UserDefaults, an API with a declared reason, as you saw in "Where Data Lives". The publishing section says where it goes.
Going deeper

what the others would require. Syncing isn't sending each change to the API. You need:

  • an identity for each task shared with the server;
  • a version or time stamp per record;
  • a rule to resolve conflicts when two devices edit the same task;
  • a queue of changes made offline that is retried when the network comes back.

The "local wins" rule stops working: with two devices, both are local. SwiftData's sync with CloudKit doesn't work with this model as it is: Apple documents in "Syncing model data across a person's devices" that CloudKit can't enforce the unique option, and TaskItem has two.

Authenticating adds a token per user and its coordinated renewal, the problem of the five 401s in "Fifteen Real-World Problems", and the uniqueness of remoteID would become per user: the case for #Unique with two properties.

Migrating matters because users already have a store with the shape of version 1's TaskItem, and version 2 has to open it. SwiftData brings the pieces: VersionedSchema describes each version of the schema, SchemaMigrationPlan lists the versions and the stages between them, and each stage (MigrationStage) is lightweight (.lightweight) or has its own code (.custom).

This app has a single schema and I didn't put that to the test. The prudent thing is to declare version 1 from the first release and test each migration by opening a store created with the previous version.

Paginating, finally: the app asks for 20 elements at once. JSONPlaceholder responded to _page and _limit in a request I made by hand on November 23, 2026 (with x-total-count and first, prev, next, and last links), but its site doesn't document it, so it's not a contract.

With your own backend, a cursor holds up better than a page number when rows are inserted while the user scrolls down, as in "Robust Networking".

Try it yourself: ⌘R: the "Tasks" title looks sharp. In the scheme (⌘< › Run › Arguments), change -ui-testing to -ui-testing-import-failure: the app opens on the error screen, with "Try Again". With -ui-testing-no-samples, it opens on the empty state.

To see the Dynamic Type fix, in the simulator open Settings › Accessibility › Display & Text Size › Larger Text and raise the size: the message scrolls instead of getting clipped. ⌘U has to count 85 tests: 77 unit tests and 8 UI tests. That's the finished app's total.

The usual mistake: an accessibility fix that brings the next problem. When I removed .borderedProminent from "Try Again", the contrast passed, but the audit said Hit area is too small; with a larger button the area passed, and Dynamic Type showed up.

In the form, the inline error as a Label kept coming out as Text clipped: inside a Form row, a Label takes on the row's icon-and-title format. With an HStack, it passed. Run the audit after each fix, not only at the end.

Check what you learned. Why isn't the blurry-title test satisfied with title.exists?

Solution

Because the blurry title was still in the accessibility tree: it existed, it could be tapped, and VoiceOver read it. What was broken was how it looked, so the test measures the pixels of its screenshot. A test has to fail with the error you want to avoid; otherwise, it doesn't protect against it.

What to take away: a review isn't adding layers; it's finding the rules written twice, the failures that lie, and the screens nobody looked at.

Download the code for step 12.

Note: you've reached the end of the app: 12 of 12 steps, about five and a half hours. What's left takes it out of the simulator.

From the Simulator to Your iPhone and the App Store

The app passes 85 tests in the simulator. What does it take to have it in your pocket, and then in someone else's? Accounts, signatures, and a couple of forms. This section is the map, with the limits and the clicks.

Note: this section is different from the rest. I ran everything before it; not this, because the Mac I built the app on doesn't have a developer account. What follows comes from the official pages of Apple and the providers, checked on November 23, 2026, and what I couldn't confirm in them is marked as unverified.

The Environment, Reviewed

What you've already used, plus what Apple's requirements ask for:

  • Xcode 27.2 needs macOS Tahoe 26.6 or later. It installs and debugs on devices with iOS 17 or later, and allows an app's minimum version to be anywhere from iOS 15 to iOS 27.
  • Xcode is downloaded from the Mac App Store. Earlier versions and betas are on the developer website, with your Apple Account and without a membership. If you install Xcode you don't need the command-line tools separately: xcodebuild only comes with Xcode.
  • From the terminal, xcode-select -s picks which Xcode to use, xcodebuild -runFirstLaunch installs the system components, and xcodebuild -downloadPlatform iOS downloads the simulator. In Xcode, the same is in Xcode › Settings › Components.

The Accounts: What Each One Lets You Do

Your Apple Account is the Apple account you already use on your iPhone. You don't need another one to develop: when you sign in with it in Xcode, Xcode shows it as a Personal Team and manages only what's needed to install on your devices. To distribute, you need the paid membership, the Apple Developer Program.

AccountWhat it allowsWhat it costsWhat it asks for
Apple Account (Personal Team)Testing on your own devices from XcodeNothingYour Apple Account
Apple Developer Program, individualTestFlight, the App Store, and the capabilities the Personal Team doesn't have99 USD per year, shown in local currency when you enrollTwo-factor authentication, legal age; your legal name appears as the seller
Apple Developer Program, organizationThe same, in the company's name, with a team of several people99 USD per yearLegal entity, D-U-N-S Number, its own website, and authority to sign
Apple Developer Enterprise ProgramOnly a company's own internal apps, without the App Store299 USD per year100 employees or more, a verification interview, and ongoing evaluation

The Personal Team's limits, which you'll notice right away:

LimitValue
App IDs you can register10, which expire after 7 days
Apps installed per device3
Validity of the profile that installs the app7 days; after that you rebuild and install again
CapabilitiesA few; there are no push notifications, iCloud, Sign in with Apple, Apple Pay, or in-app purchases

The Personal Team is enough for Native Task Manager: it doesn't use any capability.

Going deeper

the membership, in detail.

  • Individual or organization. As an individual, your legal name is the seller on the App Store; aliases and trade names aren't accepted. As an organization, it has to be a legal entity that can sign contracts with Apple, without fictitious names or branches, with a public website on its own domain and a work email on that domain. Whoever enrolls it becomes the Account Holder and must have the legal authority to bind it.
  • The D-U-N-S Number is a nine-digit identifier assigned by Dun & Bradstreet, and organizations need it, not individuals. According to Apple's enrollment help, it's free in most countries. First you check whether your organization already has one; if not, you request it. It takes up to 5 business days, plus up to 2 for Apple to receive the data.
  • How you enroll. From the Apple Developer app (iPhone, iPad, or Mac) or from the web; in India, only from the app. In the app you verify your identity by photographing an official photo ID, and the membership becomes an annual subscription that renews on its own. Individuals pay when they enroll; organizations, when Apple verifies their data and sends them an email.
  • The local price is shown during enrollment: Apple doesn't publish a table per currency, so I can't give you a figure in your currency. Nor does it publish how long it takes to approve an enrollment.
  • Fee waivers for nonprofit organizations, accredited educational institutions, and government entities that meet the requirements; not for individuals. Apple's enrollment help also says there's no program for students.

Joining a Company's Team

If you're hired for a company's app, don't pay yourself. The company enrolls as an organization and invites you to its team; it's the seller and the one that submits the app for review. The invitation is sent by the Account Holder, an Admin, or an App Manager from App Store Connect › Users and Access, and it expires after 3 days. With the same Apple Account you can be on several teams, for example if you work for several companies.

Your role decides what you can access:

RoleWhat it does
Account HolderWhoever enrolled: the only one who signs agreements, renews the membership, and requests access to the App Store Connect API
AdminSecondary contact, with almost the same responsibilities
App ManagerManages everything about an app, including submitting it for review
DeveloperDevelopment and delivery of the app
MarketingPromotional materials

There are also finance, sales, and customer support roles. An individual membership doesn't have a team: it can give access to App Store Connect to up to 50 more people, but only to App Store Connect, without the membership's other benefits.

There's No "Developer Key"

When someone asks you for "the developer key", they almost always mean one of three different things:

What gets called a "key"What it's forWho creates it
Signing certificate (Apple Development or Apple Distribution)Signing the app for a device (development) or for TestFlight and the App Store (distribution)Development ones belong to each person; distribution ones, to the team, and the Account Holder or an Admin creates them
.p8 private keyAuthenticating services like push notifications (APNs), DeviceCheck, MusicKit, or WeatherKitThe Account Holder or an Admin, in Certificates, Identifiers & Profiles › Keys; the .p8 is downloaded only once
App Store Connect API keyAutomating App Store Connect from a script or a continuous integration serverThe Account Holder first requests API access; team keys are generated by an Admin, and the private one is downloaded only once

The device clouds further down also have their own "access key", which has nothing to do with Apple.

Signing: Certificates, App IDs, and Profiles

Before it can be installed on an iPhone, an app has to be signed: carry a cryptographic mark that says who made it and that nobody changed it afterward. Three pieces are involved:

  • The bundle identifier (bundle ID) names the app across the whole system. It comes from the Organization Identifier plus the product name, in reverse-domain format. Registered in the developer account, it's called an App ID. It can't be changed after you upload the first build (the app already compiled and packaged) to App Store Connect, so pick one of your own: dev.example isn't yours.
  • The certificate says who signs.
  • The provisioning profile joins an App ID with a certificate and authorizes the app to use certain services; a development one also lists the devices it can be installed on. You can register up to 100 devices per product family and per membership year, and disabling one doesn't free up its slot.

You don't have to create any of this by hand. With Automatically manage signing turned on, Xcode registers the device and creates the development profile for you; you only pick the team and a unique bundle ID. When you distribute from the Organizer, Xcode signs with cloud-managed certificates, so you don't need the distribution one in your keychain. Capabilities (push, iCloud…) are added in the target's Signing & Capabilities tab, which only offers the ones your membership allows.

Your iPhone, Step by Step

  1. Sign in to Xcode: Xcode › Settings › Apple Accounts, "+" and your Apple Account.
  2. Automatic signing: in the navigator, the project › NativeTaskManager target › Signing & Capabilities tab. Leave Automatically manage signing checked, pick your team under Team, and change the Bundle Identifier to one of your own. If it isn't unique, Xcode warns you.
  3. Connect the iPhone to the Mac with a cable. If "Trust This Computer?" appears on the iPhone, tap Trust.
  4. Pair in Device Hub, Xcode 27's tool for simulators and devices: in the bar's destination menu, Manage Devices… (or Xcode › Open Developer Tool › Device Hub), and Pair if it appears. Pairing wirelessly from the start requires iOS 27 or later on the iPhone; after the first pairing you can continue over Wi-Fi, on the same network as the Mac and with IPv6.
  5. Turn on Developer Mode on the iPhone: Settings › Privacy & Security › Developer Mode. The toggle only appears if you've already started pairing the iPhone with a Mac. The iPhone restarts; swipe up, tap Enable, and type your passcode. Developer Mode doesn't affect what you install from the App Store or from TestFlight.
  6. Run: pick your iPhone as the destination and press ⌘R. The first time, Xcode registers the device and creates a profile that includes it.

If you update iOS on the iPhone, you have to pair it again. With a Personal Team, the app stops opening after 7 days: you press ⌘R again. If the iPhone asks you to trust the developer when you open it, Apple only documents that path for enterprise apps (Settings › General › VPN & Device Management); with a Personal Team I couldn't confirm it.

Going deeper

online verification. Apps signed for development or ad hoc by teams created after June 6, 2021 check with an Apple service the first time they're opened. Behind a corporate firewall, you have to allow https://ppq.apple.com.

Testing: Simulator, Device, TestFlight, and Device Clouds

The simulator doesn't replicate the performance or all the functions of the hardware: whatever depends on the hardware, or on performance, is tested on a device. Apple doesn't publish a closed list of what's missing from the simulator.

TestFlight is Apple's service for distributing test versions to testers, the people who test them, before publishing. It requires the membership.

Internal testersExternal testers
WhoUp to 100 people on your team, with the Account Holder, Admin, App Manager, Developer, or Marketing roleUp to 10,000 per app, by email or with a public link
Apple reviewNoYes: the first build, full review; the following ones of the same version, maybe not
RequirementAn internal groupFirst, an internal group; up to 6 builds submitted for review every 24 hours

More limits: each build can be tested for 90 days; you can share up to 100 at a time; each tester, on up to 30 devices.

The public link can be limited to a number of testers, from 1 to 10,000, and anyone can forward it. A build uploaded as TestFlight Internal Only only goes to internal groups, never to external ones or to the App Store. And TestFlight can't be offered in exchange for compensation, for example as a reward in a crowdfunding campaign.

Xcode Cloud is Apple's continuous integration and delivery (CI/CD: building and testing each change on a server, and delivering it). It builds, runs tests in parallel on simulators, and delivers through TestFlight. It requires the membership and the code in a Git repository (GitHub, GitLab, or Bitbucket). The membership includes 25 compute hours per month; the extra plans go from 100 hours for 49.99 USD per month to 10,000 hours for 3,999.99 USD.

Device clouds rent you real iPhones to run your tests or use them by hand:

ServiceWhat it offers for iOS
BrowserStack App AutomateXCUITest on real iPhones: you upload the app's .ipa (the installable package of an iOS app) and the tests' .zip through its REST API. App Live is the manual variant
Sauce LabsManual tests on real and virtual devices, and automated XCUITest on real devices with saucectl; the app is re-signed. Its documentation contradicts itself about XCUITest on simulators
AWS Device FarmXCTest and XCTest UI on physical devices and on simulators, and manual remote access. 0.17 USD per device minute, after a one-time free trial

Firebase Test Lab also runs XCTest on physical iPhones, but Google marked it as deprecated and shuts it down on September 30, 2027: don't start a new project with it.

Publishing on the App Store

App Store Connect is Apple's website where you manage a published app: its versions, its data, and its review. The path, in order:

  1. Create the app record: in App Store Connect, Apps › "+" › New App, with the same bundle ID. The Account Holder has to have accepted the latest agreement in Business.
  2. Archive and upload: in Xcode, pick Any iOS Device as the destination, Product › Archive, and in the Organizer that opens (Window › Organizer), Archives › your archive › Validate App and then Distribute App › TestFlight & App Store. You can also upload with Transporter (an Apple app for the Mac), altool (a command-line tool), or the App Store Connect API.
  3. Fill in the version's data. Required, among others: name, age rating, bundle ID, SKU (an internal code of yours for the app), content rights, primary language and category, support URL, privacy policy URL, version number, copyright, and review information.
  4. Upload the screenshots: 1 to 10 per size, in JPEG or PNG and without transparency. The ones for a medium-size iPhone with Dynamic Island are required and, if the app is for iPad, the ones for the 13-inch iPad.
  5. Declare the privacy. In App Store Connect, the privacy labels for what the app collects, including what third-party SDKs collect. Every app needs a link to its privacy policy, in App Store Connect and inside the app, and if it lets you create an account, it also has to let you delete it from the app.
  6. Add the privacy manifest, PrivacyInfo.xcprivacy: it declares the data collected and the APIs with a declared reason. Native Task Manager uses UserDefaults, so it needs one, and the tutorial app doesn't ship it: add it before you submit (see "The Privacy Manifest" in part 1).
  7. Answer the export compliance. The ITSAppUsesNonExemptEncryption key in the Info.plist avoids the questionnaire on every submission. The system's HTTPS, the one URLSession uses, is usually exempt.
  8. Fill in the age rating questionnaire. An unrated app doesn't get published.
  9. Go over the App Review Guidelines, the review rules (updated on October 16, 2026): submit final versions tested on a device, with a test account if there's sign-in and with the server running; and the app has to offer more than a packaged website.
  10. Submit for review. Apple states that it normally reviews at least 50% of submissions in under 24 hours and 90% in under 48: it's an average, not a guarantee.

For updates there's the phased release: the new version reaches users with automatic updates over 7 days, you can pause it for up to 30 days in total, and release it to everyone whenever you want. It doesn't apply to the first version.

The SDK requirements change every year, and it pays to check them before uploading:

SinceTo upload an iOS app
April 28, 2026Build with Xcode 26 or later and the iOS 26 SDK
September 9, 2026Minimum version iOS 13 or later
April 2027Build with the iOS 27 SDK or later and minimum version iOS 15 or later

Native Task Manager meets all three: it's built with Xcode 27.2 and the iOS 27.2 SDK, and its minimum is iOS 18.

The Checklist, From an Empty Mac to the App Store

The account

  • To learn or test on your iPhone, your Apple Account (Personal Team) is enough: a 7-day profile, 3 apps per device, and no push, iCloud, or Sign in with Apple.
  • For TestFlight or the App Store, enroll in the Apple Developer Program (99 USD per year; you see the local price when you enroll), as an individual or as an organization.
  • If you work for a company, ask to be invited from Users and Access with the right role; the invitation expires in 3 days.

The environment

  • macOS Tahoe 26.6 or later (sw_vers).
  • Xcode from the Mac App Store; sudo xcode-select -s /Applications/Xcode.app, and check it with xcodebuild -version.
  • Open Xcode once, or xcodebuild -runFirstLaunch.
  • The iOS simulator: Xcode › Settings › Components, or xcodebuild -downloadPlatform iOS.
  • Xcode › Settings › Apple Accounts, with your account.

The project

  • File › New › Project… › iOS › App, with an Organization Identifier of your own.
  • Signing & Capabilities: automatic signing and your team.
  • ⌘R on an iPhone simulator.

Your iPhone

  • Cable, Trust, Manage Devices…, and Pair.
  • Settings › Privacy & Security › Developer Mode, restart, and Enable.
  • Your iPhone as the destination and ⌘R. If you update iOS, pair again.

The tests

  • ⌘U: unit tests with Swift Testing and UI tests with XCTest.
  • Accessibility: performAccessibilityAudit() in the tests and Accessibility Inspector (Xcode › Open Developer Tool).
  • Performance: Product › Profile (Instruments) on a real device.
  • If you need many iPhone models: a device cloud, not Firebase Test Lab.

TestFlight

  • The app record in App Store Connect, with the same bundle ID.
  • Version and build number, icon, permission texts, PrivacyInfo.xcprivacy, and ITSAppUsesNonExemptEncryption.
  • Product › Archive › Validate App › Distribute App › TestFlight & App Store.
  • An internal group; then an external one, which goes through review.
  • Remember: each build expires after 90 days.

The App Store

  • Version data, screenshots, privacy labels, age rating, and export compliance.
  • Review information: test account, notes, and the server running.
  • The App Review Guidelines, especially testing on a device and offering more than a website.
  • A valid SDK: today Xcode 26 or later with the iOS 26 SDK; from April 2027, the iOS 27 SDK and a minimum of iOS 15.
  • Submit for review; for updates, consider the phased release.

What to take away: your Apple Account is enough for your iPhone; the membership, for everyone else's. And there's no single "key": there are certificates, .p8 keys, and API keys, each for its own purpose.

Note: last break: you now have the app and the map to publish it. What's left are the questions you'd be asked about it, about twenty minutes.

Interview Questions About the App

If you put Native Task Manager in your portfolio, in an interview they'll ask you about it. These are follow-up questions about what you built: try to answer before opening the solution.

Follow-up question 1. (Junior) Why does the app have a RemoteTodo and a TaskItem, if both describe a task?

Solution

Because they change for different reasons. RemoteTodo is the format of the API's JSON and nothing more; TaskItem is what the user owns, with fields the API doesn't have (notes, due date). Kept apart, a change in the API doesn't force you to migrate the database, and the mapping is a function you test without a network. See step 02.

Follow-up question 2. (Junior) What states does the main screen have, and why are they in an enum?

Solution

idle, loading, loaded, empty, and failed(message:). In an enum, the screen is in just one at a time, and the view's switch has to cover them all: there's no impossible combination like "loading and with an error" that two Bools would allow. isImporting and errorMessage stay outside the enum on purpose: with tasks on screen, the list stays visible while an import runs or an alert is shown. See step 06.

NativeTaskManager/Features/TaskList/TaskListView.swift
@ViewBuilder
private var content: some View {
    switch viewModel.state {
    case .idle:
        ProgressView()
    case .loading:
        ProgressView("Importing sample tasks…")
    case .empty:
        ScrollableState {
            ContentUnavailableView {
                Label("No Tasks", systemImage: "checklist")
            } description: {
                Text("Tap + to add your first task, or import a few samples.")
            } actions: {
                importButton
                    .stateActionStyle()
            }
        }
    case .failed(let message):
        ScrollableState {
            ContentUnavailableView {
                Label("Something Went Wrong", systemImage: "exclamationmark.triangle")
            } description: {
                Text(message)
            } actions: {
                // Not `.borderedProminent`: white on the accent blue failed the contrast
                // audit, and a plain text button failed "Hit area is too small".
                Button("Try Again") { viewModel.retry() }
                    .stateActionStyle()
            }
        }
    case .loaded:
        loadedList
    }
}

Follow-up question 3. (Mid) How do you guarantee that importing twice doesn't duplicate tasks or overwrite what the user edited?

Solution

The import reads the already stored remoteIDs in one go and only inserts the ones that aren't there; what's already there is skipped even if it was edited. I don't rely on @Attribute(.unique): a test showed that SwiftData turns a repeated insert into a replacement. Tests: importing twice adds zero the second time, and a local edit survives the reimport. See step 07.

NativeTaskManager/Data/TaskRepository.swift
/// Idempotent: a todo whose `remoteID` is already stored is skipped, so importing twice adds
/// nothing, and a task the user edited keeps the user's version. Imported tasks are local from
/// now on; nothing is ever sent back to the sample API.
func importTodos(_ todos: [RemoteTodo]) throws -> Int {
    let imported = try context.fetch(FetchDescriptor<TaskItem>(predicate: #Predicate { $0.remoteID != nil }))
    var known = Set(imported.compactMap(\.remoteID))
    var added = 0
    for todo in todos where !known.contains(todo.id) {
        context.insert(TaskItem(remote: todo))
        known.insert(todo.id) // also guards against a repeated id inside one response
        added += 1
    }
    try commit()
    return added
}

Follow-up question 4. (Mid) The app imports on its own at launch. How do you keep the tests from going out to the network, and how do you test the error screen?

Solution

With a decision in the composition root. If the process received -ui-testing or has the XCTestConfigurationFilePath variable (the unit tests run inside the app), the app uses an in-memory store and a fixture client. Two more arguments open the screens that a working import never shows: the error and the empty state. See steps 09 and 12.

NativeTaskManager/App/AppDependencies.swift
extension AppDependencies {
    /// The dependencies for this process. Tests never reach the network or the real store:
    /// UI tests launch the app with `-ui-testing`, and unit tests run inside the app, which XCTest
    /// marks with `XCTestConfigurationFilePath` in the environment. Two more arguments open the
    /// screens a working import never shows: the error and the empty list.
    static func forCurrentProcess(_ process: ProcessInfo = .processInfo) -> AppDependencies {
        if process.arguments.contains("-ui-testing-import-failure") {
            return .inMemory(apiClient: FixtureTodoAPIClient(failure: .offline))
        }
        if process.arguments.contains("-ui-testing-no-samples") {
            return .inMemory(apiClient: FixtureTodoAPIClient(todos: []))
        }
        let isUITesting = process.arguments.contains("-ui-testing")
        let isHostingUnitTests = process.environment["XCTestConfigurationFilePath"] != nil
        return isUITesting || isHostingUnitTests ? .inMemory() : .live()
    }
}

Follow-up question 5. (Mid) Why didn't you use @Query?

Solution

I used it in step 04, and it came out in 06. @Query lives in the view and reads the store from the environment: it's the shortest way to show data, but the logic that came later had to be tested without an interface, and that calls for a view model that receives a repository. For a screen that only shows data, @Query is still a good option.

Follow-up question 6. (Mid) A save fails. What does the user see, and what stays stored?

Solution

An alert, and the list as it's stored. The repository saves with commit(), which on a failure calls rollback() and rethrows the error; without that, the next read would include the pending change and the row would show it as done. Six tests force the failure with the injected save function. See step 12.

NativeTaskManager/Data/TaskRepository.swift
extension SwiftDataTaskRepository {
    /// Saves, or puts the context back to what is stored. Without the rollback a failed save
    /// leaves the change pending in the context: fetches include pending changes and autosave
    /// may store it later, so the list would show a change the alert says was not saved.
    private func commit() throws {
        do {
            try saveChanges(context)
        } catch {
            context.rollback()
            throw error
        }
    }
}

Follow-up question 7. (Mid) If the screen disappears in the middle of an import, what happens to the request?

Solution

It's cancelled. The import is a task the view model keeps; the view calls cancelImport() in .onDisappear, and cancelling the task cancels the URLSession request, which throws a URLError with the code .cancelled. The view model doesn't show an error for that. In this app I only observed it when the scene was destroyed; sending the app to the background didn't trigger .onDisappear. See step 08.

Follow-up question 8. (Senior) You're asked to make two iPhones of the same user see the same tasks. What changes?

Solution

Almost everything that's "local" today. You need a backend that really stores data, an identity for each task shared with the server, a version or time stamp per record, a rule to resolve conflicts, a queue of offline changes with retries, and authentication.

SwiftData's sync with CloudKit doesn't work as is: it doesn't support the unique attributes TaskItem has. Before writing code, I'd decide who wins in a conflict, because that defines the model. See step 12.

Follow-up question 9. (Senior) In version 2 you add a property to TaskItem. What happens to the users of version 1?

Solution

They have a store with version 1's schema, and version 2 has to open it. If ModelContainer(for:) can't, it throws an error, and in this app that ends in live()'s fatalError. That's why the migration is planned before publishing: each schema version with VersionedSchema, the stages between them in a SchemaMigrationPlan, lightweight or with code, and a test that opens a store created with the previous version.

Also say what you'd do with the new property on the old rows: a default value or a stage with code. See step 12.

What You Learned

  • An iOS project comes out of the Xcode template with two changes: Swift 6 mode in all three targets and iOS 18 as the minimum in the project. The template's concurrency settings (MainActor by default only in the app, Approachable Concurrency) decide how everything else compiles.
  • The network's format (RemoteTodo, nonisolated and Decodable) and the model you store (TaskItem, a @Model) are different types, joined by a tested mapping.
  • The list, the validated form, and their sheets are run by an @Observable view model that receives a repository and a client through its initializer, from a composition root.
  • The import uses URLSession and Codable with an explicit timeout, shows loading, empty, success, and error, doesn't hide data when the network fails, and is cancelled along with the screen.
  • SwiftData is the source of truth: the import looks before it inserts, and a failed save is undone with rollback().
  • An architecture review finds rules written twice, failures that lie, and screens nobody audited, and each finding is closed with a test that fails for the right reason.
  • 85 tests guard the app without a network: 77 unit tests with a fake URLProtocol, in-memory SwiftData, and hand-written doubles, and 8 UI tests that drive the app the way VoiceOver does and audit the list, the form, and the empty and error states. No automated test covers the on-disk store, the data surviving a relaunch, or the real network (the tests use an in-memory store and fake responses): I checked that by hand, importing 20 real tasks and seeing that they were still there after relaunching.
  • From the simulator to the App Store: your Apple Account for your iPhone, the membership for TestFlight and the App Store, automatic signing, and the list of what a publication asks for.
  • The follow-up questions prepare you to defend each of those decisions in an interview.

What's Next

This part ends the series. You started with let and var in the terminal and you finish with an app that has data, states, accessibility, 85 tests, and a path to the App Store, and with the reasons behind each decision so you can defend it in an interview.

What comes next is yours. Three challenges to extend Native Task Manager, each with what the series has already taught you:

Junior challenge: the app in Spanish. Add a String Catalog (File › New › File from Template…, String Catalog template) and translate the interface text into Spanish. You've done it when, with the simulator in Spanish (Settings › General › Language & Region), the list says "Tareas" and the UI tests still pass in English. Follow-up question: which UI test queries depend on the language, and how would you make them independent?

Solution

Queries by visible text (app.buttons["Add Task"]) depend on the language; the fixture's titles don't, because they're data. There are two ways: fix the app's language in the UI tests, or look up by a stable identifier only the controls that have no natural text. The criterion: the test keeps reading the app the way VoiceOver does, and doesn't break when the simulator's language changes.

Mid challenge: a detail screen. When you tap a task, push a detail screen with NavigationStack instead of opening the sheet, and move the import to a screen that can be closed. You've done it when, on leaving that screen during an import, the request is cancelled and no error appears, and a UI test checks it. Follow-up question: what does your .onDisappear do if the user sends the app to the background?

Solution

Navigate with a NavigationStack(path:) and a value per task, as in "Navigation With NavigationStack". The cancellation is already in the view model; what's new is that the screen that imports can disappear.

For the test, use a client that takes a long time (like HangingTodoAPIClient) behind a launch argument. The criterion: it cancels when you leave the screen, and it doesn't leave the import flag written. Check for yourself what happens when you send the app to the background: in this app, that didn't trigger .onDisappear.

Senior challenge: version 2 of the schema. Add a priority to TaskItem with a versioned schema (VersionedSchema for version 1 and 2, and a SchemaMigrationPlan). You've done it when a test creates a store with version 1 in a temporary file, opens it with version 2, and checks that the tasks are still there with a default priority. Follow-up question: what would you change if the priority came from the API and had no default value?

Solution

Declare SchemaV1 with the current TaskItem and SchemaV2 with the new property and its default value, and a plan with a stage from 1 to 2: lightweight if SwiftData can infer it, with code if values have to be computed. The test can't use an in-memory store, because it has to open the same file with two schemas. The criterion: the migration is tested with data from the previous version, not only with a new store.

And one question for you, before we close: of all the app's decisions, which would you make differently in a project of your own, and which test would you write first to defend your version?

Bibliography

The sources were consulted between November 19 and 23, 2026.