Back to articles

What the Screen Doesn't Show: Data, Tests, and Fifteen iOS App Failures Fixed

Created by Manuel Herrera Mesén ·

Part 3 of 4iosswiftdatatestingperformanceserie-ios
Download as PDF · 83 pp.

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

You type a long task, leave it half done, and switch to another app. An hour later you come back and the text is gone: the system closed the app to reclaim memory, and nobody had saved it. Another day you get a new iPhone, restore your backup, and the app asks you to sign in again. And one morning the list is slow to respond when you tap it, without a single error on screen.

None of those problems shows up when you read a view. They depend on what isn't on the screen: where each piece of data is stored, what a test checks, and what a tool measures. Part 2 ended with a view model that asks a repository for its data.

Here you decide what sits behind that repository, how you test it without a network, and how you diagnose fifteen typical failures, each with a fix I ran.

Time and fast track. The whole part takes about three hours with the examples. If you have 45 minutes, read where data lives, the Keychain, Tests, and three cases: the retain cycle, the five 401s, and no network at launch.

The part closes with nine interview questions and five exercises.

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 comparison with React Native closes this part). The day-to-day this part shows is choosing where to store each piece of data, writing tests, and finding out why the app freezes.

It costs a Mac with Xcode; the paid developer account is only needed to publish, in part 4. If you enjoy finding out why something fails, this is for you. The full box is in part 1.

By the end of this part you will be able to:

  1. choose where each piece of data goes (preferences, files, and caches, the Keychain, or SwiftData) by sensitivity, shape, and lifetime;
  2. save a secret in the Keychain with the most restrictive accessibility that works;
  3. invalidate a cache by time or by version, and tell no-cache from no-store;
  4. write unit tests without a network or a real database, and UI tests with an accessibility audit;
  5. pick the debugging tool that fits each symptom;
  6. diagnose fifteen real-world problems, from symptom to prevention;
  7. compare native Swift with React Native using documented facts;
  8. answer questions 24 to 32 and solve exercises 16 to 20.
Going deeper

how to read this guide and how I verified the code. The main text goes step by step and is written for people who are starting out. The examples and the The usual mistake boxes are for when you implement and debug. The Going deeper boxes, like this one, hold the detail for people who weigh decisions.

When the text says "the example's test", it means the automated tests I used to check each example: they are in the downloadable projects, and in "Tests" you learn to write them.

I ran all of it with Xcode 27.2 (27B52) and Swift 6.4.2. The data and testing examples are Swift packages that passed their tests with swift test on macOS 27.2; they declare iOS 18 as their platform, so the same code compiles for iOS. I tested the Keychain inside a minimal app, with tests hosted on an iPhone 17 simulator running iOS 27.2.

Fourteen of the fifteen problems are programs that ran on Linux, in the official Swift 6.4.2 Docker image and without a network; each one ran three times with the same output. The lost session has no program of its own: it reuses the SessionManager from p3-datos.

The outputs and error messages are the ones the tools printed, copied verbatim. When I measured something instead of reading it in the documentation, the text says so. There are no timing figures: the examples count operations (requests, decodes, rows), which come out the same on any machine.

Before You Start

Do you have what you need? A Mac with Xcode 27.2, and parts 1 and 2 read. Download the four projects for this part; the title of each code block says which file it comes from:

  • p3-datos.zip: preferences, files, caches, SwiftData, and the session.
  • p3-llavero.zip: Keychain Lab, a one-screen app that saves and deletes a token.
  • p3-calidad.zip: tests with Swift Testing and XCTest, a fake server, and the Thread Sanitizer program.
  • p3-problemas.zip: one program per real-world problem, fourteen in all (the lost session reuses SessionManager from p3-datos), three interview exercises, and the short programs from the cache section.
Going deeper

what to review first, and the settings each project compiles with.

From part 2 this part uses Codable and URLSession, actors, Sendable, the Observable macro, and the view model with an injected repository.

  • p3-datos and p3-calidad are Swift packages: open them in Xcode with File › Open… (pick their Package.swift) and run their tests with Product › Test (⌘U).

    They compile in Swift 6 mode with the language's default isolation: nothing belongs to the main actor unless it says so, which is why the UI types have @MainActor written out.

  • p3-llavero is an Xcode project with two settings from the template, MainActor by default and Approachable Concurrency, and one changed by hand: Swift 6 language mode (the template ships Swift 5).

    They live in the project navigator › project › TARGETS › KeychainLab, Build Settings tab, settings Swift Language Version, Default Actor Isolation, and Approachable Concurrency. Without them, some examples won't compile the same way.

  • p3-problemas holds single-file programs with no Apple frameworks. They run with swiftc -swift-version 6 File.swift -o program && ./program, on macOS or Linux.

The series app, Native Task Manager, is built in part 4. This part doesn't need it: when a topic has its version in the app, the text links to the step where it appears.

Where Data Lives

An app stores very different things: a preference ("show completed tasks"), an access token (the credential the app sends to the server with every request), hundreds of tasks the user filters and sorts, a draft, the thumbnails of some downloaded images.

If everything goes to the same place, something goes wrong: a token in an unencrypted preferences file, hundreds of records in a settings dictionary, or images you could download again taking up room in the user's backup.

To choose, ask three questions about the data:

  1. Is it secret? A token, a password, or a key goes to the Keychain, which has its own section. The other stores on this list add no encryption of their own: they are protected only by the system's data protection, which doesn't stop anyone from reading them while the device is unlocked.
  2. What shape does it have? A single value, many records you query with filters, or a whole document.
  3. How long does it live, and can you get it again? Whatever you can download again is cache: the system may delete it, and it shouldn't go in the backup.
A decision tree that starts with "is it secret?" (yes: Keychain) and continues with "is it a small setting?" (UserDefaults), "is it user data you query?" (SwiftData, with Core Data underneath), "is it a document or a blob of bytes?" (a file in Application Support or Documents), and "can it be downloaded again?" (Caches, URLCache, or NSCache in memory). Each leaf says whether the app encrypts the data and whether it goes into the backup.
Three questions decide where a piece of data goes: whether it's secret, what shape it has, and whether you can get it again.

Preferences: UserDefaults

UserDefaults is the app's preferences store: key-value pairs of simple types (a Bool, a number, a string, a date) that the system saves to disk. Apple's documentation says it plainly: it stores them unencrypted. That's why it's for settings that aren't secret, and nothing else.

Four facts worth knowing before you use it:

  • It's thread-safe. A thread is a sequence of instructions the system runs; an app has several at once, and the main one is the one that draws the interface. You can use the same UserDefaults object from several threads or tasks at once, and it writes to disk asynchronously.
  • Don't call synchronize(). Apple marks it as unnecessary and says not to use it: it dates from when you had to force the write by hand.
  • There's no documented size limit for iOS. The only published limit is tvOS's. Having no number isn't permission to store long lists: the guidance is to use it for small settings.
  • It's a required reason API: if your app uses it, your privacy manifest, PrivacyInfo.xcprivacy, has to say why. Since May 1, 2024, App Store Connect doesn't accept apps that use one of these APIs without declaring it. You saw the manifest in part 1.

If you come from the web, UserDefaults plays the same role as localStorage: key and value, unencrypted, for the app itself. It's similar, with one difference: it stores typed values, not just strings.

The example stores two preferences. The UserDefaults object isn't created inside: it comes in through the initializer. The app passes .standard, the usual one; the tests pass a suite of their own, a separate preferences store with its own name, created with UserDefaults(suiteName:).

p3-datos/Sources/DataStorage/AppSettings.swift
/// Small, non-sensitive preferences. The UserDefaults object is injected:
/// the app passes `.standard`, the tests pass a suite of their own.
struct AppSettings {
    private let defaults: UserDefaults
 
    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
        // Values used while the user has not chosen anything. They are not written to disk.
        defaults.register(defaults: [Keys.showsCompleted: true])
    }
 
    var showsCompletedTasks: Bool {
        get { defaults.bool(forKey: Keys.showsCompleted) }
        nonmutating set { defaults.set(newValue, forKey: Keys.showsCompleted) }
    }
 
    var lastOpenedTab: Int {
        get { defaults.integer(forKey: Keys.lastTab) } // 0 if it was never set
        nonmutating set { defaults.set(newValue, forKey: Keys.lastTab) }
    }
 
    private enum Keys {
        static let showsCompleted = "settings.showsCompletedTasks"
        static let lastTab = "settings.lastOpenedTab"
    }
}

Step by step:

  • register(defaults:) provides the value used while the user hasn't chosen anything: here, show completed tasks. That value isn't written to disk; the example's test checks it by reading what was stored in the suite: the key isn't there.
  • bool(forKey:) returns false and integer(forKey:) returns 0 when the key doesn't exist. That's why it pays to register an initial value when "not chosen" shouldn't be false or 0.
  • The sets are nonmutating because the struct doesn't change: the UserDefaults object it holds does.
  • The keys live in one place, Keys, so you never write the same string twice with one letter different.

The example's test creates a suite with a unique name (UserDefaults(suiteName:)), writes and reads both values through two different instances of AppSettings, and at the end deletes the suite with removePersistentDomain(forName:). It never touches the machine's real preferences.

See it yourself: unzip p3-datos.zip, open it in Xcode with File › Open… (pick Package.swift), and press ⌘U. In the Test navigator (⌘6), AppSettingsTests shows up with its three tests in green.

The usual mistake: storing the access token in UserDefaults because it's one line of code away. It sits on disk unencrypted, and a bearer token can be used by anyone who has it, with no other proof of identity (RFC 6750; an RFC is the document that sets an Internet standard). The token goes in the Keychain.

Files: FileManager

FileManager is the API for creating folders and reading, writing, moving, and deleting files. You use it when the data is a document or a blob of bytes: a draft in JSON, an exported PDF, an image the user created.

Where you write matters as much as what you write. Since iOS 16, URL exposes the main folders as properties:

FolderWhat foriCloud backup?
URL.documentsDirectoryThe user's documentsYes
URL.applicationSupportDirectoryData the app needs and the user doesn't handle as filesYes
URL.cachesDirectoryWhatever you can regenerate or download againNo: the system purges it from time to time
URL.temporaryDirectoryShort-lived working filesNo: the system purges it from time to time

Apple documents that tmp and Library/Caches stay out of the backup because the system purges them. If a file in another folder can be regenerated, you can mark it with isExcludedFromBackup, but that's a hint to the system, not a guarantee: Apple makes clear it doesn't promise the file will never show up in a backup, and recommends marking it again every time you save it.

The example saves drafts as JSON. As before, the folder comes in from outside: the app uses Application Support and the test, a fresh temporary folder.

p3-datos/Sources/DataStorage/DraftFileStore.swift
/// Saves drafts as JSON files in a directory it receives.
struct DraftFileStore {
    let directory: URL
 
    /// In the app: Application Support, which is backed up and not purged by the system.
    static func live() -> DraftFileStore {
        DraftFileStore(directory: URL.applicationSupportDirectory.appending(path: "Drafts"))
    }
 
    func save(_ draft: Draft, named name: String) throws {
        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
        let encoder = JSONEncoder()
        encoder.outputFormatting = .sortedKeys
        // .atomic writes to a temporary file and then replaces the old one:
        // a crash halfway never leaves half a JSON on disk.
        try encoder.encode(draft).write(to: fileURL(named: name), options: .atomic)
    }
 
    func load(named name: String) throws -> Draft? {
        do {
            return try JSONDecoder().decode(Draft.self, from: Data(contentsOf: fileURL(named: name)))
        } catch CocoaError.fileReadNoSuchFile {
            return nil // no draft yet; asking "does it exist?" first would race with a delete
        }
    }
 
    private func fileURL(named name: String) -> URL {
        directory.appending(path: "\(name).json")
    }
}

That's how you avoid the first scene of the opening: if the draft is written to a file when the scene moves to the background (the scene phase from part 1), the text is still there even if the system closes the app.

.atomic writes to a temporary file first and then replaces the old one: if the app quits halfway, the disk keeps the whole old file, never half a JSON. The encoder uses .sortedKeys so the file always comes out the same; the example's test reads the file's text and compares it with {"notes":"Oat, not soy","title":"Buy milk"}.

It also checks that a draft that doesn't exist returns nil and that live() points to Drafts inside Application Support.

See it yourself: in p3-datos, ⌘U: DraftFileStoreTests shows up in green with its three tests in the Test navigator (⌘6).

In-Memory Cache: NSCache

NSCache is an in-memory dictionary meant for things you can recompute: an already decoded image, an expensive result. Three differences from a dictionary make it useful:

  • it's thread-safe: you can read and write from several threads at once without a lock of your own;
  • it evicts on its own: when the system needs memory, it removes entries without telling you;
  • its limits, such as countLimit, aren't strict, and the order in which it evicts isn't guaranteed.
p3-datos/Sources/DataStorage/ThumbnailCache.swift
/// NSCache stores objects (classes), so the decoded image goes in a small wrapper.
final class Thumbnail {
    let pixels: Data
    init(pixels: Data) { self.pixels = pixels }
}
 
/// A memory cache that the system may empty at any time: a miss is normal,
/// and the caller recomputes or downloads again.
struct ThumbnailCache {
    private let storage = NSCache<NSURL, Thumbnail>()
 
    init(countLimit: Int) {
        storage.countLimit = countLimit // a hint, not a strict limit
    }
 
    func thumbnail(for url: URL) -> Thumbnail? {
        storage.object(forKey: url as NSURL)
    }
 
    func insert(_ thumbnail: Thumbnail, for url: URL) {
        storage.setObject(thumbnail, forKey: url as NSURL)
    }
}

NSCache stores objects, not structs: that's why the thumbnail goes inside a small class and the key is NSURL. Because the system can empty it at any moment, a cache miss is normal: whoever uses it has to know how to recompute or download again.

The example's test checks only what's guaranteed: what you insert can be read while it's still there, and it's the same object (===). It doesn't test eviction, because neither the timing nor the order is guaranteed: a test like that would pass or fail depending on the machine's free memory.

See it yourself: in p3-datos, ⌘U: ThumbnailCacheTests shows up in green in the Test navigator (⌘6).

HTTP Cache: URLCache

URLCache is URLSession's cache of HTTP responses, in memory and on disk. You don't create it for each piece of data: it comes with the session's configuration. A default session uses the shared cache; an ephemeral session, a private one held only in memory; a background session, none.

Two documented facts and one that isn't:

  • On iOS, the disk cache can be purged when space runs low, but only while the app isn't running.
  • What gets stored and when it's reused is decided by the response's cache headers; you see them in "Offline, Caching, and Invalidation".
  • The shared cache's default sizes aren't documented. If you need them, set them yourself when you create the session.

How to Decide

DataWhereDoes the app encrypt it?Backed up?Why
The tab the user opened lastUserDefaultsNoYesSmall setting, not secret
The access tokenKeychainYes (the system encrypts it)Depends on the accessibility you chooseSecret
Hundreds of tasks with filtersSwiftDataNoYesRecords you query
A draft or a PDFFile in Application Support or DocumentsNoYesA whole document
Downloaded thumbnailsCaches or NSCacheNoNoYou can get them again
API responsesURLCacheNoNoHTTP governs them

Check what you learned. Would you store the number of the last tab the user opened in the Keychain?

Solution

No. It isn't secret: if someone reads it, they gain nothing. It's a small setting, and its place is UserDefaults. The Keychain is for whatever would grant access to something if it leaked.

Going deeper

the usual reason for UserDefaults in the privacy manifest is CA92.1: reading and writing data that only the app itself can access. If you share settings with an extension through an App Group, the reason is a different one, 1C8F.1.

What to take with you: before you store a piece of data, ask whether it's secret, what shape it has, and whether you can get it again; the three answers pick the store.

The Keychain

Where do you put the token so that no other app, and nobody who copies your app's files, can read it? The Keychain is the system's secrets store: Apple describes it as an encrypted database for small pieces of user data, such as passwords and tokens. Unlike UserDefaults, you don't program the encryption: the system does it. You decide when each item can be read.

The Four Functions

The Keychain API is a C API with four functions. They all take a dictionary that describes the item and return an OSStatus, a number that says how the operation ended:

FunctionWhat it doesResults you'll see
SecItemAddAdds an itemerrSecSuccess, or errSecDuplicateItem if it already exists
SecItemCopyMatchingSearches and returnserrSecSuccess, or errSecItemNotFound
SecItemUpdateChanges an existing itemerrSecSuccess, or errSecItemNotFound
SecItemDeleteDeleteserrSecSuccess, or errSecItemNotFound

A token is a "generic password": the class kSecClassGenericPassword. Two attributes identify it: the service (kSecAttrService, the name of your app or your API) and the account (kSecAttrAccount, here "access" or "refresh").

When It Can Be Read: Accessibility

Every item carries an accessibility (kSecAttrAccessible): the device state in which it can be read. The table shows the most common options, not all of them. If you don't set one, the value is kSecAttrAccessibleWhenUnlocked: readable while the iPhone is unlocked. Apple recommends choosing the most restrictive option that works for your app.

ValueCan be readWhen to use it
kSecAttrAccessibleWhenUnlockedThisDeviceOnlyWhile the device is unlocked, and only on this deviceA token the app uses only in the foreground
kSecAttrAccessibleWhenUnlockedWhile the device is unlocked (the default)If the item should travel to another iPhone with an encrypted backup
kSecAttrAccessibleAfterFirstUnlockFrom the first unlock after startupIf the app needs it in the background (…AfterFirstUnlockThisDeviceOnly if it also shouldn't migrate)
kSecAttrAccessibleAlwaysAlwaysNever: Apple marked it obsolete in iOS 12

The variants that end in ThisDeviceOnly don't migrate: if the user restores the backup on another device, those items don't arrive. That's what you want for a token tied to a session, and it explains the second scene from the opening: on a new iPhone there's no token, and the app asks you to sign in again. It's a chosen behavior, not a bug.

A Secrets Store

The example wraps the four functions in a small type. It lives in Keychain Lab, the one-screen app in p3-llavero, and its tests run hosted inside that app, the same path a real app follows.

p3-llavero/KeychainLab/KeychainStore.swift
/// Stores small secrets (an access token, a refresh token) as generic passwords.
/// `nonisolated`: this app target is MainActor by default, and Keychain calls
/// block the calling thread, so they must not run on the main actor.
nonisolated struct KeychainStore: Sendable {
    let service: String
 
    struct Failure: Error, Equatable {
        let status: OSStatus
    }
 
    /// Adds the secret, or replaces it if the account already has one.
    @concurrent func save(_ secret: Data, for account: String) async throws {
        var item = baseQuery(account)
        item[kSecValueData as String] = secret
        // Most restrictive option that still works for a foreground app:
        // readable only while unlocked, and never migrated to another device.
        item[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
 
        let status = SecItemAdd(item as CFDictionary, nil)
        if status == errSecDuplicateItem {
            // The update sets the accessibility again: an item saved by an older version of
            // the app could still have a less restrictive one.
            let changes = [
                kSecValueData as String: secret,
                kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
            ] as CFDictionary
            let updated = SecItemUpdate(baseQuery(account) as CFDictionary, changes)
            guard updated == errSecSuccess else { throw Failure(status: updated) }
        } else if status != errSecSuccess {
            throw Failure(status: status)
        }
    }
 
    /// The secret, or nil if there is none.
    @concurrent func read(_ account: String) async throws -> Data? {
        var query = baseQuery(account)
        query[kSecReturnData as String] = true
        query[kSecMatchLimit as String] = kSecMatchLimitOne
 
        var result: CFTypeRef?
        let status = SecItemCopyMatching(query as CFDictionary, &result)
        switch status {
        case errSecSuccess: return result as? Data
        case errSecItemNotFound: return nil
        default: throw Failure(status: status)
        }
    }
 
    /// Deleting something that is not there is not an error.
    @concurrent func delete(_ account: String) async throws {
        let status = SecItemDelete(baseQuery(account) as CFDictionary)
        guard status == errSecSuccess || status == errSecItemNotFound else {
            throw Failure(status: status)
        }
    }
 
    private func baseQuery(_ account: String) -> [String: Any] {
        [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
        ]
    }
}

Step by step:

  • nonisolated and @concurrent. Keychain Lab has the main actor by default, like a new Xcode app. Apple documents that SecItemAdd blocks the thread that calls it, and that calling it from the main thread can freeze the interface; it says the same about the other three functions. That's why the type is nonisolated and every method is @concurrent: it always runs off the main actor.

    With Approachable Concurrency, a nonisolated async method without @concurrent would run on the caller's actor, which from a view is the main actor (you saw it in part 2).

  • Saving is adding or updating. SecItemAdd doesn't replace: if there's already an item with that service and that account, it returns errSecDuplicateItem. In that case the method calls SecItemUpdate with the new value.

  • Reading asks for a single result. kSecReturnData asks for the bytes and kSecMatchLimitOne for a single item. errSecItemNotFound isn't an error for the reader: it means "no token", and the method returns nil.

  • Deleting what isn't there doesn't fail. That way sign-out can be called twice.

  • The C part. The API comes from Core Foundation, the system's C layer. kSecClass as String turns a C constant into a Swift String; as CFDictionary does the opposite with the dictionary; CFTypeRef? is "any Core Foundation object, or nothing", and &result passes the variable so the function can write the result into it.

  • An update sets the accessibility again. An item saved by an older version of the app could have a less restrictive one; the update tightens it.

The tests run hosted in Keychain Lab, on the simulator, with a uniquely named service per test so they don't collide. They check what was saved and deleted, the errSecDuplicateItem of the second SecItemAdd, the item's accessibility (also after updating an old one), and that SecItemCopyMatching without kSecMatchLimit returns a single item.

The OSStatus values are the API's contract: that's why the tests assert them.

You see them in full in "Tests", once you know how to read them.

See it yourself: unzip p3-llavero.zip, open KeychainLab.xcodeproj, pick an iPhone simulator in Xcode's top bar, and press ⌘U (Product › Test). In the Test navigator (⌘6) you see KeychainStoreTests with its seven tests in green.

Note: if you'd rather build Keychain Lab yourself: File › New › Project…, iOS › App template, Product Name KeychainLab, Interface SwiftUI, and under Testing System the Swift Testing option (UI tests stay in XCTest).

Then in the target, Build Settings tab, set Swift Language Version to Swift 6. Add KeychainStore.swift with File › New › File from Template… › Swift File, checking the KeychainLab target, and replace ContentView.swift with the one in "UI Tests".

That view asks for a store, so the app stops compiling until you also change KeychainLabApp.swift: create the KeychainStore and pass ContentView(store: store), like the KeychainLabApp.swift block in that same section.

Last, the tests. Add KeychainStoreTests.swift with the same menu, checking the KeychainLabTests target, with the block from the "Swift Testing" box. Replace the contents of KeychainLabUITests.swift, which the template already created in the KeychainLabUITests target, with the block from "UI Tests".

The article's blocks start after the import lines, so write them yourself: import Foundation and import Security in KeychainStore.swift; import SwiftUI in ContentView.swift (delete the rest of the template's file, its #Preview too); import XCTest in KeychainLabUITests.swift; and import Foundation, import Security, import Testing, and @testable import KeychainLab in KeychainStoreTests.swift. That makes them match the files in p3-llavero.

The usual mistake: treating errSecDuplicateItem as a failure and showing the user an error the second time they sign in. It isn't a failure: it's the signal to update the item.

Check what you learned. Why isn't SecItemAdd called from code isolated to the main actor?

Solution

Because it blocks the calling thread while the system writes. From the main actor that thread is the main thread, and the interface stops responding during the call. In the example, @concurrent always moves it off the main actor.

Going deeper

several apps from the same team, or an app and its extensions, can share items through an access group (kSecAttrAccessGroup). This series doesn't use them: Native Task Manager has no extensions or accounts, and a group adds signing configuration that contributes nothing to what's being taught.

Another design decision: the store doesn't keep the token in memory between calls. Reading it each time costs a system call, but that way signing out from anywhere deletes the only copy.

What to take with you: a secret goes to the Keychain, with the most restrictive accessibility that works and always off the main actor.

SwiftData and Core Data

When the data is many records you filter and sort (an app's tasks, for example), UserDefaults falls short, and a JSON file forces you to read the whole thing for every query. What you need is a database.

SwiftData is Apple's persistence framework (a library that ships with the system) for Swift: you describe your models with Swift classes and it takes care of saving and querying them. It's built on Core Data, the persistence framework Apple has had since iOS 3, and it exists since iOS 17.

The Model

p3-datos/Sources/DataStorage/TodoItem.swift
@Model
final class TodoItem {
    @Attribute(.unique) var remoteID: Int
    var title: String
    var isCompleted: Bool
    var updatedAt: Date
 
    init(remoteID: Int, title: String, isCompleted: Bool = false, updatedAt: Date) {
        self.remoteID = remoteID
        self.title = title
        self.isCompleted = isCompleted
        self.updatedAt = updatedAt
    }
}
  • @Model turns the class into a persistent model: the macro makes it conform to PersistentModel and Observable, and declares Sendable as unavailable. That's why SwiftUI finds out when a property changes, as with part 2's @Observable.
  • @Attribute(.unique) asks that no two rows share the same remoteID. It exists since iOS 17. For a constraint over several properties together, for example user plus identifier, there's the #Unique macro, which is from iOS 18.
  • It's a class, not a struct: each row is an object with identity, and whatever you change in it gets saved.

Container, Context, and Queries

Three pieces work together:

PieceWhat it is
ModelContainerThe database: the schema and where it's stored (on disk, or only in memory)
ModelContextWhere you insert, change, delete, and query; it saves with save()
FetchDescriptorA query: which rows (#Predicate), in what order (SortDescriptor), and how many
p3-datos/Sources/DataStorage/TodoItem.swift
/// The store on disk in the app; only in memory in tests and previews.
func makeTodoContainer(inMemory: Bool) throws -> ModelContainer {
    let configuration = ModelConfiguration(isStoredInMemoryOnly: inMemory)
    return try ModelContainer(for: TodoItem.self, configurations: configuration)
}
 
func addTodo(remoteID: Int, title: String, at date: Date, to context: ModelContext) throws {
    context.insert(TodoItem(remoteID: remoteID, title: title, updatedAt: date))
    try context.save() // explicit: this code does not depend on autosave
}
 
/// Completed to-dos, most recently updated first.
func completedTodos(in context: ModelContext) throws -> [TodoItem] {
    let descriptor = FetchDescriptor<TodoItem>(
        predicate: #Predicate { $0.isCompleted },
        sortBy: [SortDescriptor(\.updatedAt, order: .reverse)]
    )
    return try context.fetch(descriptor)
}

\.updatedAt is a key path: a reference to the updatedAt property of any TodoItem, not its value; the SortDescriptor uses it to know what to sort by. ModelConfiguration(isStoredInMemoryOnly: true) creates a database that lives only in memory: each test starts empty and leaves nothing on disk.

#Predicate is a macro that turns the closure into a condition the database understands; it isn't a closure that runs row by row in Swift.

The example's test creates an in-memory container, inserts three tasks with different dates, marks one as completed, and checks that completedTodos returns only that one, and that the order by descending date is 3, 2, 1.

See it yourself: in p3-datos, ⌘U again: SwiftDataTests and TodoImporterTests show up in green in the Test navigator (⌘6). If you change the order to .forward in latestTodos (the function you see next), the ordering test fails and Xcode shows you both arrays.

How Many Rows: fetchLimit

p3-datos/Sources/DataStorage/TodoItem.swift
/// The `limit` most recently updated to-dos; `nil` returns all of them.
func latestTodos(limit: Int?, in context: ModelContext) throws -> [TodoItem] {
    var descriptor = FetchDescriptor<TodoItem>(
        sortBy: [SortDescriptor(\.updatedAt, order: .reverse)]
    )
    descriptor.fetchLimit = limit // the documented "no limit" is nil, not 0
    return try context.fetch(descriptor)
}

The test checks that a limit of 2 returns the two most recent and that nil returns all three.

What I Measured

I wanted to see three SwiftData behaviors before teaching them. I wrote a program that prints them, DataProbe, and ran it on macOS; the same three checks ran as tests hosted on the iOS 27.2 simulator and gave the same result. To see it yourself, in Terminal, inside the p3-datos folder: swift run DataProbe.

mainContext.autosaveEnabled: true
ModelContext(container) made on the main actor: true
ModelContext(container) made off the main actor: false
fetchLimit = 2: 2 of 3
fetchLimit = nil: 3 of 3
fetchLimit = 0: 3 of 3
rows with key 1 after a second insert: 1, title: inserted again

What each line means:

  1. Autosave. The documentation says autosaveEnabled is false by default and that SwiftData sets it to true on the container's mainContext (the context the container comes with, already created and bound to the main actor) and on the one SwiftUI's modelContainer modifier creates. Measured: a context created with ModelContext(container) from the main actor also came out true; one created off the main actor, false.

    The documented part is the mainContext rule; the rest is what this version did. The practical conclusion doesn't change: if your code needs something saved, call save(), as addTodo does.

  2. fetchLimit = 0 returned every row, same as nil. That 0 means "no limit" isn't documented: what's documented is nil. Write nil.

  3. A second insert with the same unique attribute didn't raise an error: it left a single row with the second one's data. In other words, it behaved like an update (an upsert). If you import data from a server and rely on that to avoid duplicates, the import overwrites whatever the user edited on the phone. Exercise 16 solves the import without depending on it.

The usual mistake: creating the container and keeping only the context, let context = try makeTodoContainer(inMemory: true).mainContext.

The context doesn't keep its container alive: as soon as the container was released, using the context stopped the test process with a trap signal (the forced stop you saw with ! on nil in part 1), without a useful message.

Keep the container somewhere that lives as long as the context: in the app, at the composition root (where the app creates its dependencies at launch); in a test, in a property of the type that groups the tests.

@Query or a View Model

SwiftUI ships @Query: a view property that runs a query and redraws the view when the data changes.

It's the shortest way to show SwiftData data. The part 4 app uses it in its first list and then replaces it with a view model and a repository, for the reason you saw in part 2: the logic for filtering, importing, and showing errors gets tested without bringing up any view.

With @Query, the query lives in the view, and testing it requires the view.

Check what you learned. You create a context with ModelContext(container) inside a @concurrent function, insert a task, and don't call save(). Is it saved?

Solution

There's no guarantee. The documentation only promises autosave for the mainContext, and in the measurement a context created off the main actor had autosaveEnabled set to false. If the change has to persist, call save().

Going deeper

Core Data is still the choice when you already have a Core Data store in production, or when you need something SwiftData doesn't offer on your minimum iOS version. On concurrency: ModelContext isn't Sendable, so a context isn't shared between actors.

@Model doesn't make the model Sendable (the compiler rejects sending it across actors: the conformance is marked unavailable), and the model belongs to its context: across actors, pass its persistentModelID (a PersistentIdentifier) and look it up with model(for:) in a context on the other side.

A p3-datos test does it from a @concurrent function and finds the same row.

When the schema changes between app versions, you'll need migrations: step 12 of part 4 explains which pieces SwiftData brings for that (VersionedSchema and SchemaMigrationPlan). And not every query has to fetch everything:

propertiesToFetch limits the attributes (an empty array fetches all of them, not none) and relationshipKeyPathsForPrefetching brings the relationships in the same query. In the usual terms: by default relationships load lazily (they're read from the store when you touch them, which Core Data calls faulting), and relationshipKeyPathsForPrefetching loads them eagerly, along with the query.

What to take with you: in SwiftData, save with save() and measure what isn't documented before you rely on it.

Note: a good place for a break. You've covered where data lives, the Keychain, and SwiftData: about 28% of the part, some 50 of its 180 minutes. Next come the session, caching, and tests.

Sessions: Stateful and Stateless

You sign in once and make a hundred requests. How does the server know the hundredth one is yours too? There are two ways:

  • With state on the server. When you sign in, the server creates a session and gives you an identifier, usually in a cookie (a piece of data the server asks the client to keep and that comes back with every request). Every request carries the identifier, and the server looks up the session in its memory or its database.
  • Stateless. Every request carries everything needed to understand it, including the credential: a token in the Authorization: Bearer … header. It's the stateless interaction constraint Roy Fielding defined for REST.

An app with tokens has two:

  • the access token, which goes on every request and is short-lived;
  • the refresh token, used to ask for a new access token without typing the password again. The authorization server decides whether to issue one: it's optional in OAuth 2.0, the authorization standard that defines these tokens (RFC 6749).

Both are secrets: they go in the Keychain. The example's session manager doesn't know the Keychain exists: it receives anything that conforms to the SecretStore protocol. In the app, the implementation calls a store like the KeychainStore from the previous section; in the tests, it's a dictionary inside an actor.

One simplification before the code: if signIn's second save fails, you're left with an access token without the refresh token. In production, store both in a single Keychain item (for example, encoded together) or delete the first if the second fails.

p3-datos/Sources/DataStorage/SessionManager.swift
/// Where secrets live. In the app, the Keychain; in tests, a dictionary.
protocol SecretStore: Sendable {
    func read(_ account: String) async throws -> String?
    func save(_ value: String, for account: String) async throws
    func delete(_ account: String) async throws
}
 
enum SessionState: Equatable {
    case unknown   // before reading the store at launch
    case anonymous
    case signedIn
}
 
/// Owns the session on the client: the tokens go to the store, never to UserDefaults.
/// @Observable so a SwiftUI view can show sign-in or the app depending on `state`.
@MainActor
@Observable
final class SessionManager {
    private(set) var state: SessionState = .unknown
    private let store: any SecretStore
 
    init(store: any SecretStore) {
        self.store = store
    }
 
    /// At launch: a session exists only if there is an access token in the store.
    /// A read that fails (for example, the device is locked) is not "signed out":
    /// the state stays `.unknown` and the caller tries again later.
    func restore() async throws {
        let token = try await store.read("access")
        state = token == nil ? .anonymous : .signedIn
    }
 
    func signIn(accessToken: String, refreshToken: String) async throws {
        try await store.save(accessToken, for: "access")
        try await store.save(refreshToken, for: "refresh")
        state = .signedIn
    }
 
    func signOut() async throws {
        try await store.delete("access")
        try await store.delete("refresh")
        state = .anonymous
    }
 
    /// The header every request carries: each request is self-contained.
    func authorizationHeader() async throws -> String? {
        guard let token = try await store.read("access") else {
            state = .anonymous // the token is gone: show sign-in, do not fail silently
            return nil
        }
        return "Bearer \(token)"
    }
}
  • The class is @Observable (you saw it in part 2): a view that reads state redraws when it changes, and that's how it decides whether to show sign-in or the app.
  • The state starts at .unknown: at launch, the app hasn't read the store yet. If the interface showed "no session" at that instant, the user would see the sign-in screen flicker.
  • restore() decides with a single fact: if there's an access token, there's a session. If the read fails (the Keychain won't let you read a WhenUnlocked item while the device is locked), the error propagates and the state stays at .unknown: a read failure isn't the same as "no session", and treating them alike would sign out someone whose phone was merely locked.
  • authorizationHeader() is what the HTTP client uses on every request. If the token disappeared, the state moves to .anonymous and the interface shows sign-in, instead of sending requests without a credential that fail one after another.

The example's tests use an in-memory store and check five things: with no token, restore() leaves the session at .anonymous; signing in saves both tokens and signing out deletes them; with a token already saved, restore() gives .signedIn; if the token disappears from outside, asking for the header returns nil and leaves the session at .anonymous; and with a store whose reads fail, restore() throws the error and the state stays at .unknown.

See it yourself: in p3-datos, ⌘U: SessionManagerTests shows up in green with its five tests in the Test navigator (⌘6).

401 and 403 Aren't Handled the Same

RFC 6750, which defines how bearer tokens are used, gives the criterion: an invalid or expired token (invalid_token) gets a 401; a valid token that isn't enough for what was asked (insufficient_scope), a 403. The client's rule follows from that:

  • on a 401, refresh the token once and retry once;
  • on a 403, don't refresh: another token with the same permissions gets the same answer.

The case of five 401s at once is in "Fifteen Real-World Problems".

Check what you learned. Why does a 401 trigger a token refresh and a 403 doesn't?

Solution

The 401 says the credential doesn't work (for example, it expired): a new token can fix it. The 403 says the server understood who you are and won't let you in: a new token with the same permissions gets another 403. Refreshing there only wastes a request.

Going deeper

as you saw in "Where Data Lives", a bearer token needs no other proof of identity. Three rules follow that don't depend on the framework: the token doesn't go in UserDefaults, doesn't go in the logs, and doesn't go in the URL, because URLs end up in server logs and in history.

The client session doesn't replace the server's either: signing out in the app deletes the tokens from the phone, but if the server offers to revoke them, sign-out should call it.

What to take with you: the client's session is a token in the Keychain; a 401 is refreshed once, a 403 isn't.

Offline, Caching, and Invalidation

A cache speeds up the app and lets it work without a network, but it brings a problem the version without a cache didn't have: the copy can be stale. Invalidation is deciding when a stored copy can no longer be used as is. There are two tools, and HTTP defines both.

By Time: max-age

A response with Cache-Control: max-age=43200 says: "this response is fresh for 43,200 seconds (12 hours)". That period is its time to live, or TTL. After that time, RFC 9111 considers it stale: keeping it isn't forbidden, but before using it you have to ask the server, unless there's no connection: without a network, the RFC allows serving a stale copy.

JSONPlaceholder, the series' sample API, serves its todos with that same max-age; I observed it on November 19, 2026.

The example decides whether a copy is fresh. The clock isn't read inside: the instant is a parameter, so the program can ask "and 13 hours from now?" without waiting 13 hours.

p3-problemas/CacheTTL.swift
/// A stored response and the freshness lifetime its server gave it (Cache-Control: max-age).
struct CachedResponse {
    let body: String
    let storedAt: Date
    let maxAge: TimeInterval
 
    /// Stale once its age is greater than max-age (RFC 9111). The clock is a parameter.
    func isFresh(at now: Date) -> Bool {
        now.timeIntervalSince(storedAt) <= maxAge
    }
}
 
let storedAt = Date(timeIntervalSince1970: 1_800_000_000)
let todos = CachedResponse(body: "[200 todos]", storedAt: storedAt, maxAge: 43_200) // 12 h
 
for hours in [1, 12, 13] {
    let now = storedAt.addingTimeInterval(Double(hours) * 3600)
    print("after \(hours) h:", todos.isFresh(at: now) ? "fresh, use it" : "stale, revalidate")
}
after 1 h: fresh, use it
after 12 h: fresh, use it
after 13 h: stale, revalidate

See it yourself: in the p3-problemas folder, run swiftc -swift-version 6 CacheTTL.swift -o ttl && ./ttl: it prints the three lines above.

Going deeper

at the exact boundary, the RFC isn't consistent. The max-age definition says "stale when its age is greater", and the formula in its section 4.2 (freshness_lifetime > current_age) already treats it as stale when they're equal. The code picks <=; what matters is deciding and testing it.

Two directives always get mixed up, and they say different things:

DirectiveCan it be stored?Can it be reused without asking?
no-cacheYesNo: it has to be revalidated with the server before each use
no-storeNo: neither the request nor the response—

no-cache doesn't mean "don't store". What forbids storing is no-store.

By Version: ETag and 304

Revalidating is asking the server "is what I have still good?" without downloading the whole response. For that, the server sends an ETag with each response: an opaque identifier for that version of the resource. It can be strong ("abc") or weak (W/"abc"), which says "equivalent", not "identical byte for byte".

On the next request, the client sends it back in If-None-Match. If the resource didn't change, the server answers 304 Not Modified, with no body: the client uses its copy. If it changed, it answers 200 with the new body and another tag.

RFC 9110 requires comparing If-None-Match with the weak comparison: that's why a W/ tag works for revalidation. JSONPlaceholder sends weak ETags and, with If-None-Match, answered 304 (observed on November 19, 2026).

Four stacked layers, from fastest to slowest: memory (NSCache), URLCache (HTTP, according to Cache-Control), disk (SwiftData or files), and network. An arrow from the network to the copy says "revalidate with ETag → 304, the copy stays"; another, "TTL expired → ask before using".
Each layer answers if it can; if not, it asks the next one. The network decides whether a copy is still good.

The example is a revalidating cache written by hand, so you can see each step:

p3-datos/Sources/DataStorage/ConditionalClient.swift
/// GET with revalidation: it keeps the last body and its ETag, sends If-None-Match,
/// and on a 304 returns the body it already had.
actor ConditionalClient {
    enum Failure: Error, Equatable {
        case status(Int)
        case notModifiedWithoutCopy
    }
 
    private struct Cached {
        let etag: String
        let body: Data
    }
 
    private let session: URLSession
    private var cache: [URL: Cached] = [:]
 
    init(session: URLSession) {
        self.session = session
    }
 
    func data(from url: URL) async throws -> Data {
        var request = URLRequest(url: url)
        if let cached = cache[url] {
            request.setValue(cached.etag, forHTTPHeaderField: "If-None-Match")
        }
        let (body, response) = try await session.data(for: request)
        let status = (response as? HTTPURLResponse)?.statusCode ?? 0
 
        switch status {
        case 304:
            // Read the cache again after the await: another call may have changed it.
            guard let cached = cache[url] else { throw Failure.notModifiedWithoutCopy }
            return cached.body
        case 200..<300:
            if let etag = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "ETag") {
                cache[url] = Cached(etag: etag, body: body)
            } else {
                cache[url] = nil // no validator: an old ETag would ask about a body we replaced
            }
            return body
        default:
            throw Failure.status(status)
        }
    }
}
  • It's an actor because the dictionary of copies is read and written from concurrent requests.
  • If there's a copy, the request carries If-None-Match with its tag.
  • On 304, it returns the stored body. It looks it up after the await: during the request, the actor may have served another call that changed the cache (the reentrancy from part 2).
  • On 200, it stores the new body and tag.

The example's test uses a fake server inside URLSession (you build it in "A Fake Server"). The first response is a 200 with ETag: W/"1"; the second, a 304 with no body. The test checks that the first request went out without If-None-Match, that the second carried it with W/"1", and that the client returned the same body both times.

Another test checks that a 200 with W/"2" replaces the copy, and a third, that a 404 is an error.

See it yourself: in p3-datos, ⌘U: ConditionalClientTests shows up in green in the Test navigator (⌘6), including the test that checks that a response without an ETag drops the old copy.

Why not use URLCache, which already exists? For a real app it may be the choice: it's URLSession's HTTP cache. Here I wrote it out explicitly for two reasons: you see each step, and the test doesn't depend on how URLCache treats a fake protocol's responses.

The test uses a copy of the fake server that returns a list of responses in order, and its session has urlCache = nil: with two caches, you wouldn't know which one answered.

Without a Network: the Local Copy Rules

An app that works offline treats its local database as the source of truth: the interface shows what's stored, and the network only updates it. If the network fails, the screen doesn't switch to "error": it keeps showing what's stored, with a notice. You see it working in the "No network at launch" case.

A Lazy Property Isn't a Data Cache

A lazy property (lazy var) is a stored property whose initial value is computed the first time someone reads it, not when the instance is created.

p3-problemas/LazyProperty.swift
final class ReportScreen {
    // Computed on first access, once per instance, and kept in memory.
    lazy var summary: String = {
        print("computing summary")
        return "3 tasks, 1 completed"
    }()
}
 
let screen = ReportScreen()
print("screen created")
print(screen.summary)
print(screen.summary)        // already computed: no second "computing"
 
let another = ReportScreen() // a new instance computes its own
print(another.summary)
screen created
computing summary
3 tasks, 1 completed
3 tasks, 1 completed
computing summary
3 tasks, 1 completed

See it yourself: in the p3-problemas folder, run swiftc -swift-version 6 LazyProperty.swift -o lazy && ./lazy: "computing summary" shows up twice, once per instance.

The computation runs once per instance, the first time it's read, and the result stays in memory while the object lives. It's useful for an expensive value that may never be needed. It has nothing to do with when SwiftData fetches rows from the database: that's decided by the FetchDescriptor, with fetchLimit and the relationship prefetching you saw in SwiftData.

A lazy var doesn't survive the app closing either, nor does it invalidate itself: if the data it depends on changes, it keeps returning the first value.

Check what you learned. The user changes the filter summary depends on after reading it once. Is it recomputed?

Solution

No. A lazy var is computed once per instance, the first time it's read; if the data changes, it keeps returning the first value. For a value that depends on others that change, use a computed property or recompute on purpose.

Check what you learned. A response arrives with Cache-Control: no-cache. Can it be stored?

Solution

Yes. no-cache allows storing it, but requires revalidating it with the server before each use, for example with If-None-Match. The one that forbids storing is no-store.

Going deeper

showing a stale copy while revalidating in the background is a common product practice; exercise 17 puts an age limit on it. The hard part of offline mode isn't reading, it's writing: if the user edits on the phone without a network and someone else edits the same thing on the web, somebody decides who wins (last writer, or a field-by-field merge).

The part 4 app avoids the problem on purpose: it imports once from a read-only API and from then on owns its tasks, with no syncing. Real syncing would need per-record versions and a conflict response from the server, such as 409.

What to take with you: every stored copy has an expiry date or a version tag; without one of them, you can't tell whether it's still true.

Tests: Swift Testing, XCTest, and Test Doubles

You change one line of the form's validator. How do you know, without opening the app, that it still works? A unit test is code that runs a small piece of your app (a function, a type) with data you choose and checks the result, with no interface, no network, and no real database.

It's much faster than a UI test and always gives the same result, so you run it every time you change something. All the claims of "the example's test" in the earlier sections are unit tests.

Apple has two testing frameworks, and they live side by side in the same target:

Swift TestingXCTest
SinceXcode 16Long before; still included
A test isA function with @TestA test… method on a subclass of XCTestCase
Checking#expect(a == b), #require(…)XCTAssertEqual(a, b) and family
Data-driven cases@Test(arguments:)A loop, or one method per case
UI testsNoYes (XCUIAutomation)

The practical rule: Swift Testing for new unit tests; XCTest for UI tests and for code that already has them. Don't mix the assertions: use the ones from each test's framework. In a package like p3-calidad, mixing them can hide a failure; the box at the end of "XCTest" shows it.

Swift Testing

The piece I'm testing is the form's title validation:

p3-calidad/Sources/Quality/TitleValidator.swift
enum TitleProblem: Equatable, Sendable {
    case empty
    case tooLong(count: Int)
}
 
/// The rules of the app's form: trimmed, not empty, at most 80 characters.
func validateTitle(_ raw: String) -> TitleProblem? {
    let title = raw.trimmingCharacters(in: .whitespacesAndNewlines)
    if title.isEmpty { return .empty }
    if title.count > 80 { return .tooLong(count: title.count) }
    return nil
}

And these are its tests:

p3-calidad/Tests/QualityTests/TitleValidatorTests.swift
struct TitleValidatorTests {
    // One test, four cases: each argument runs and is reported on its own.
    @Test("Title rules", arguments: [
        ("Buy milk", nil),
        ("", TitleProblem.empty),
        ("   \n", .empty),
        (String(repeating: "a", count: 81), .tooLong(count: 81)),
    ] as [(String, TitleProblem?)])
    func validates(input: String, expected: TitleProblem?) {
        #expect(validateTitle(input) == expected)
    }
 
    @Test func eightyCharactersAreAllowed() {
        #expect(validateTitle(String(repeating: "a", count: 80)) == nil)
    }
 
    @Test func decodesTheFixture() throws {
        let todos = try JSONDecoder().decode([Todo].self, from: Fixtures.threeTodos)
        // #require stops the test here if there is no first element:
        // the next line would make no sense without it.
        let first = try #require(todos.first)
        #expect(first.title == "delectus aut autem")
        #expect(todos.filter(\.completed).isEmpty)
    }
}
  • @Test marks a function as a test. The quoted text is the name you'll see in the report.
  • arguments: runs the same function once per element. Each case is reported separately: if the 81-character one fails, you see which it was, and the other three keep running.
  • #expect checks a condition. If it fails, it records the failure with the values it saw and the test continues.
  • #require also checks, but if it fails, it stops the test (it throws an error). Use it when the following lines make no sense without that condition: here, unwrapping the first element before reading its title.
  • The 80-character edge case has its own test: bugs hide at the edges.
  • Fixtures.threeTodos is a fixture: fixed data stored next to the tests. Here it's the first three JSONPlaceholder tasks, copied from a real response.
Going deeper

the complete Keychain tests, hosted in Keychain Lab. They use what you just saw, plus two pieces: try #require to unwrap the attributes the Keychain returns, and @Suite(.serialized), which makes the type's tests run one after another instead of in parallel, because they share the simulator's Keychain.

p3-llavero/KeychainLabTests/KeychainStoreTests.swift
/// Hosted in the KeychainLab app on the simulator: the Keychain needs a host app.
/// Each test uses its own service name and cleans up after itself.
@Suite(.serialized)
struct KeychainStoreTests {
    let store = KeychainStore(service: "dev.example.KeychainLab.tests.\(UUID().uuidString)")
 
    @Test func savedSecretReadsBackEqual() async throws {
        let secret = Data("access-token-1".utf8)
        try await store.save(secret, for: "access")
        #expect(try await store.read("access") == secret)
        try await store.delete("access")
    }
 
    @Test func readingAMissingItemGivesNil() async throws {
        #expect(try await store.read("nobody") == nil)
    }
 
    @Test func secondAddReturnsDuplicateAndSaveUpdates() async throws {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: store.service,
            kSecAttrAccount as String: "refresh",
            kSecValueData as String: Data("first".utf8),
        ]
        #expect(SecItemAdd(query as CFDictionary, nil) == errSecSuccess)
        // The same service + account again: the Keychain refuses a second item.
        #expect(SecItemAdd(query as CFDictionary, nil) == errSecDuplicateItem)
 
        // save(_:for:) resolves the duplicate with SecItemUpdate.
        try await store.save(Data("second".utf8), for: "refresh")
        #expect(try await store.read("refresh") == Data("second".utf8))
        try await store.delete("refresh")
    }
 
    @Test func deleteRemovesTheItemAndIsIdempotent() async throws {
        try await store.save(Data("x".utf8), for: "access")
        try await store.delete("access")
        #expect(try await store.read("access") == nil)
        try await store.delete("access") // errSecItemNotFound is not an error here
    }
 
    @Test func itemIsStoredWithTheRequestedAccessibility() async throws {
        try await store.save(Data("x".utf8), for: "access")
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: store.service,
            kSecAttrAccount as String: "access",
            kSecReturnAttributes as String: true,
        ]
        var result: CFTypeRef?
        #expect(SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess)
        let attributes = try #require(result as? [String: Any])
        let accessible = try #require(attributes[kSecAttrAccessible as String] as? String)
        #expect(accessible == kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String)
        try await store.delete("access")
    }
 
    @Test func copyMatchingReturnsOnlyOneItemByDefault() async throws {
        try await store.save(Data("a".utf8), for: "one")
        try await store.save(Data("b".utf8), for: "two")
        // Same service, two accounts; no kSecMatchLimit: one result, not a list.
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: store.service,
            kSecReturnAttributes as String: true,
        ]
        var result: CFTypeRef?
        #expect(SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess)
        #expect(result is [String: Any])
        #expect((result as? [[String: Any]]) == nil)
        try await store.delete("one")
        try await store.delete("two")
    }
 
    @Test func updatingAnOldItemAlsoTightensItsAccessibility() async throws {
        let old: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: store.service,
            kSecAttrAccount as String: "legacy",
            kSecValueData as String: Data("old".utf8),
            kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked, // saved by an older version
        ]
        #expect(SecItemAdd(old as CFDictionary, nil) == errSecSuccess)
        try await store.save(Data("new".utf8), for: "legacy")
 
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: store.service,
            kSecAttrAccount as String: "legacy",
            kSecReturnAttributes as String: true,
        ]
        var result: CFTypeRef?
        #expect(SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess)
        let attributes = try #require(result as? [String: Any])
        #expect(attributes[kSecAttrAccessible as String] as? String
                == kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String)
        try await store.delete("legacy")
    }
}

XCTest

The same logic, in XCTest, plus a test of an API that answers late, in a closure:

p3-calidad/Tests/QualityTests/LegacyCheckerXCTests.swift
final class TitleValidatorXCTests: XCTestCase {
    func testRejectsAnEmptyTitle() {
        XCTAssertEqual(validateTitle(""), .empty)
        XCTAssertNil(validateTitle("Buy milk"))
    }
 
    /// The API answers later, in a callback: the test waits for an expectation.
    /// `async` plus `await fulfillment(of:)` is the wait that is safe with Swift concurrency.
    func testTheCallbackArrives() async {
        let answered = expectation(description: "the checker calls back")
        LegacyTitleChecker().check("") { problem in
            XCTAssertEqual(problem, .empty)
            answered.fulfill()
        }
        // Without a timeout, the default is to wait forever.
        await fulfillment(of: [answered], timeout: 2)
    }
}
  • The class inherits from XCTestCase; every method whose name starts with test is a test.
  • XCTAssertEqual compares two values; XCTAssertNil, that something is nil.
  • For code that reports back through a closure, the test creates an expectation (expectation), fulfills it inside the closure (fulfill()), and waits with fulfillment(of:timeout:). Apple presents it as the safe way to wait in code that uses Swift concurrency, instead of the old wait(for:). Its default timeout is infinite: always give it a timeout.
  • An async XCTest test runs on an arbitrary actor if you don't say which one. If it touches main-actor code, mark it @MainActor.

The closure test calls the checker with an empty title and expects to receive .empty in under two seconds. The checker answers 50 milliseconds later, from another queue.

Going deeper

why not mix the two frameworks' assertions. Swift 6.4 lets you use #expect inside XCTest and an XCTest assertion inside Swift Testing, but in an existing project, or in a package with a swift-tools-version earlier than 6.4, a failing XCTAssert inside a @Test is reported only as a warning. I measured it with a small package on 6.2, like p3-calidad:

p3-calidad/InteropProbe/Tests/ProbeTests/MixedAssertionTests.swift
@Test func xctAssertInsideSwiftTesting() {
    XCTAssertEqual(answer, 42) // 41 != 42: does the test fail?
}
⚠︎ Test xctAssertInsideSwiftTesting() recorded a warning at MixedAssertionTests.swift:7:1: Issue recorded
⚠︎ Test xctAssertInsideSwiftTesting() recorded a warning at MixedAssertionTests.swift:7:1: An API was misused
↳ Replace XCTest API such as 'XCTAssert' with a Swift Testing equivalent such as '#expect'.
✔ Test run with 1 test in 0 suites passed after N seconds with 2 warnings.

The test compares 41 with 42 and passes, with two warnings. With swift-tools-version: 6.4 the same code fails. In Xcode, you change the mode in the test plan (it says which tests the scheme runs, and with which settings; the scheme is the build-and-run configuration you pick under Product › Scheme):

Product › Scheme › Edit Test Plan, Configurations tab, "Swift Testing and XCTest Interoperability" setting. A new project uses a plan that Xcode creates on its own, with no file: the first time you edit it, Xcode asks where to save it.

Outside the test plan, the mode comes from an environment variable (a named value a program reads from its environment when it starts): SWIFT_TESTING_XCTEST_INTEROP_MODE, with the values none, limited, complete, or strict. It isn't a build setting: the testing framework reads it at run time. With swift-tools-version: 6.4, SWIFT_TESTING_XCTEST_INTEROP_MODE=limited swift test passes again with the two warnings. In Xcode, test environment variables go in that same Configurations tab of the plan, under Environment Variables.

A Fake Server: URLProtocol

Testing an HTTP client against the real server has three problems: the test fails when the network fails, the data changes, and you can't trigger a 404 or a 500 whenever you want. The solution is to inject into the client a URLSession whose only destination is a fake server.

URLProtocol is the Foundation class URLSession uses to load each URL. If you register a subclass of your own in the session's configuration (protocolClasses), that subclass receives the requests and decides what to answer. If you come from the React series, it plays the same role as MSW: it intercepts requests at the client's network layer.

p3-calidad/Tests/QualityTests/StubURLProtocol.swift
/// A fake server that lives inside URLSession. Each test registers what to answer
/// for a URL; the stub records every request it receives.
final class StubURLProtocol: URLProtocol {
    struct Reply: Sendable {
        var status = 200
        var headers: [String: String] = ["Content-Type": "application/json"]
        var body = Data()
    }
 
    private struct Registry {
        var replies: [URL: Reply] = [:]
        var requests: [URLRequest] = []
    }
 
    // URLSession creates the protocol objects itself, so the shared state is static,
    // behind a lock: requests can arrive from any thread.
    private static let registry = Mutex(Registry())
 
    static func reply(_ reply: Reply, for url: URL) {
        registry.withLock { $0.replies[url] = reply }
    }
 
    static func requests(to url: URL) -> [URLRequest] {
        registry.withLock { $0.requests.filter { $0.url == url } }
    }
 
    /// An ephemeral session whose only custom protocol is this one.
    static func session() -> 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 reply = Self.registry.withLock { registry -> Reply? in
            registry.requests.append(request)
            return request.url.flatMap { registry.replies[$0] }
        }
        guard let reply, let url = request.url,
              let response = HTTPURLResponse(url: url, statusCode: reply.status,
                                             httpVersion: "HTTP/1.1", headerFields: reply.headers)
        else {
            // An unregistered URL is a mistake in the test: fail like a network without a route.
            client?.urlProtocol(self, didFailWithError: URLError(.cannotFindHost))
            return
        }
        client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
        client?.urlProtocol(self, didLoad: reply.body)
        client?.urlProtocolDidFinishLoading(self)
    }
 
    override func stopLoading() {}
}
  • URLSession creates the protocol instances on its own, so whatever the test registers has to live somewhere static. Requests arrive from any thread: the registry sits behind a Mutex (from the Synchronization module, macOS 15 and iOS 18).
  • startLoading() records the request, looks up the response for that URL, and hands it to the client with three calls: the response, the body, and the end. A URL with no registered response fails like a host that doesn't exist: it's a test bug, and you want it to show.

The client under test receives the session in its initializer. Its tests:

p3-calidad/Tests/QualityTests/TodoClientTests.swift
struct TodoClientTests {
    // A different host per test: the stub is shared, the URLs are not.
    let base = URL(string: "https://client-tests-\(UUID().uuidString).invalid")!
 
    @Test func sendsAcceptAndDecodesTheFixture() async throws {
        let url = base.appending(path: "todos")
        StubURLProtocol.reply(.init(body: Fixtures.threeTodos), for: url)
        let client = TodoClient(session: StubURLProtocol.session(), baseURL: base)
 
        let todos = try await client.todos()
 
        #expect(todos.map(\.id) == [1, 2, 3])
        let sent = try #require(StubURLProtocol.requests(to: url).first)
        #expect(sent.value(forHTTPHeaderField: "Accept") == "application/json")
    }
 
    @Test func aNon200IsAnErrorBeforeDecoding() async throws {
        let url = base.appending(path: "todos")
        StubURLProtocol.reply(.init(status: 404, body: Data("{}".utf8)), for: url)
        let client = TodoClient(session: StubURLProtocol.session(), baseURL: base)
 
        await #expect(throws: ClientError.status(404)) {
            try await client.todos()
        }
    }
}

Swift Testing runs tests in parallel. Since the fake server's registry is shared, each test uses a different host (client-tests-<uuid>.invalid) and doesn't overwrite the others' responses. The .invalid domain is reserved: it never resolves, so if a request escaped to the real world, it would fail.

What these tests can't give you: the fake server doesn't prove JSONPlaceholder still answers that way. That's covered by the fixture, copied from a real response on November 19, 2026, and a review when the API changes. Two documented limits of protocolClasses: the session checks its default protocols first and yours afterward, and a custom URLProtocol doesn't work with background sessions.

Even so, in these tests, putting [StubURLProtocol.self] in protocolClasses was enough for the fake to answer every request.

See it yourself: unzip p3-calidad.zip, open it in Xcode (File › Open…, Package.swift), and press ⌘U. In the Test navigator (⌘6) you see the Swift Testing tests (TitleValidatorTests, TodoClientTests, EmailValidatorTests) and the XCTest ones (TitleValidatorXCTests), all in green. Change 80 to 79 in validateTitle and test again: the 80-character case fails.

The usual mistake: using URLSession.shared inside the client. The test can no longer change the session and ends up talking to the real server: it passes on your Mac and fails on a train with no signal.

Check what you learned. You want to check that an optional isn't nil and then read one of its properties. #expect or #require?

Solution

#require. If the value is nil, the test stops right there with a clear message, instead of carrying on and failing on the next line for a reason that explains nothing.

Going deeper

the double I used in "Sessions" (InMemorySecretStore) and the fake server are two different styles. The first replaces a dependency you defined yourself with a protocol: it's part 2's dependency injection.

The second replaces a piece of the system you can't change, URLSession, through its official extension point. Prefer the first when the boundary is yours: it's shorter and doesn't depend on how URLSession loads. Use the second when what you want to test is precisely the code that builds the request and reads the response.

What to take with you: inject what you don't control (the network session, the store, the clock) and the test stops depending on the world.

Note: another possible break. You're about 46% in, some 85 minutes: you can already store, invalidate, and test. What's left is the UI, the tools, the fifteen cases, and the interview.

UI Tests and Accessibility

Unit tests don't know whether the button exists, can be tapped, or can be read. A UI test launches the app on the simulator and uses it through its interface: it finds a button by its text, taps it, and waits for something to appear on screen.

It runs in a separate process from the app, so it can't call your code: it only sees the app's accessibility tree (labels, traits, and identifiers). It's much slower than a unit test, and that's why it covers the important flows, not every rule.

UI tests are written with XCTest, in a target of their own: Xcode's app template already creates it (you see it in step 01 of part 4). XCUIApplication represents the app under test; Apple now documents it in the XCUIAutomation framework, and it's isolated to the main actor: that's why every test carries @MainActor.

The Keychain Lab test walks through its only screen and then asks for an audit:

p3-llavero/KeychainLabUITests/KeychainLabUITests.swift
final class KeychainLabUITests: XCTestCase {
    override func setUpWithError() throws {
        continueAfterFailure = false // in a UI test, stop at the first failure
    }
 
    @MainActor
    func testSavingAndDeletingTheToken() throws {
        let app = XCUIApplication()
        app.launchArguments = ["-ui-testing"] // the app switches to a test-only Keychain service
        app.launch()
 
        let status = app.staticTexts["status"]
        app.buttons["Delete the token"].tap() // start from a known state
        XCTAssertTrue(status.wait(for: \.label, toEqual: "No token saved", timeout: 5))
 
        app.buttons["Save a sample token"].tap()
        XCTAssertTrue(status.wait(for: \.label, toEqual: "A token is saved", timeout: 5))
 
        app.buttons["Delete the token"].tap()
        XCTAssertTrue(status.wait(for: \.label, toEqual: "No token saved", timeout: 5))
    }
 
    @MainActor
    func testAccessibilityAudit() throws {
        let app = XCUIApplication()
        app.launchArguments = ["-ui-testing"]
        app.launch()
        // No assertions: the test fails by itself if the audit finds a problem.
        try app.performAccessibilityAudit()
    }
}
  • Launch arguments. launchArguments passes -ui-testing to the app, and the app, on seeing it, uses a Keychain service of its own for tests. It's how you give the test known data without touching the user's. In the part 4 app, the same argument swaps the network for a fixture and the database for an in-memory one.
  • Find things by what the user sees. Buttons are found by their text; the status, by an accessibility identifier (status) the view assigns to it.
  • Wait, don't sleep. wait(for:toEqual:timeout:) waits until the label takes the value, or fails when the deadline passes. A fixed pause would be slow when there's time to spare and short when there isn't.
  • Start from a known state. The test deletes the token before starting, in case an earlier run left it saved.

These are the two app hooks the test depends on. The launch argument picks the Keychain service:

p3-llavero/KeychainLab/KeychainLabApp.swift
// UI tests launch the app with -ui-testing: it then uses a Keychain service of its own,
// so a test never reads or deletes what a normal run saved.
private let store = KeychainStore(
    service: ProcessInfo.processInfo.arguments.contains("-ui-testing")
        ? "dev.example.KeychainLab.ui-tests"
        : "dev.example.KeychainLab"
)

And the whole screen, with the identifier the test looks for on the status text:

p3-llavero/KeychainLab/ContentView.swift
/// The host app's only screen: save, read and delete one sample token.
struct ContentView: View {
    let store: KeychainStore
    @State private var status = "Checking…"
 
    var body: some View {
        VStack(spacing: 20) {
            Text("Keychain Lab")
                .font(.largeTitle.bold())
            Text(status)
                .accessibilityIdentifier("status") // what the UI test looks for
            Button("Save a sample token") {
                Task { await run { try await store.save(Data("sample-token".utf8), for: "access") } }
            }
            .buttonStyle(.borderedProminent)
            // The accessibility audit flagged white text on the default blue as low contrast
            // ("Contrast nearly passed"): a darker blue fixes it.
            .tint(Color(red: 0.0, green: 0.35, blue: 0.75))
            Button("Delete the token", role: .destructive) {
                Task { await run { try await store.delete("access") } }
            }
            // Same audit, second finding: the default destructive red on white. A darker red.
            .foregroundStyle(Color(red: 0.7, green: 0.0, blue: 0.0))
        }
        .padding()
        .task { await run {} }
    }
 
    /// Runs a Keychain operation and then shows what is stored. An error is shown, not swallowed.
    private func run(_ operation: () async throws -> Void) async {
        do {
            try await operation()
            status = try await store.read("access") == nil ? "No token saved" : "A token is saved"
        } catch let failure as KeychainStore.Failure {
            status = "Keychain error \(failure.status)"
        } catch {
            status = "Keychain error"
        }
    }
}

See it yourself: in Keychain Lab, ⌘U also runs KeychainLabUITests: you'll see the simulator open the app, tap both buttons, and close it, and the two UI tests in green in the Test navigator (⌘6).

The Accessibility Audit

performAccessibilityAudit() (iOS 17, Xcode 15) checks the current screen for accessibility problems: contrast, size of tap targets, elements without a label, text that gets cut off at large font sizes. It takes no assertions: if it finds something, the test fails on its own.

On Keychain Lab, the audit failed twice on contrast, with the same message: "Contrast nearly passed" and, in the full description, "Contrast is not high enough for SwiftUI.AccessibilityNode unless font size is larger." The first time, the element was the "Save a sample token" button: .borderedProminent style, white text on the default blue.

I fixed it with a darker blue (.tint(Color(red: 0, green: 0.35, blue: 0.75))) and the audit failed again, now on "Delete the token": the default destructive red on white. With a darker red (.foregroundStyle(Color(red: 0.7, green: 0, blue: 0))), it passed. It isn't a made-up case: it's what the tool found on a screen with three elements.

Beyond the audit, three things are checked by hand before shipping:

  • Accessibility Inspector, on the simulator: Xcode › Open Developer Tool › Accessibility Inspector. You point at an element and see its label, traits, and identifier, the same things the test reads.
  • VoiceOver, iOS's screen reader, on a physical iPhone: Apple says it isn't available on the simulator. Turn it on in Settings › Accessibility › VoiceOver, walk through the screen, and listen for whether each element says what it is and what it does.
  • Dynamic Type, the text size the user picks: with the app running on the simulator, in Xcode's debug bar, Environment Overrides button › Text, turn the size up to the maximum and check that nothing gets cut off.

And one rule for the code: a button with only an icon needs accessibilityLabel, and a state told apart only by color also needs a shape or a text.

The full version of this test, for Native Task Manager (create, complete, filter, and delete a task, and audit the list in light and dark mode), is in step 11 of part 4.

Check what you learned. Why shouldn't a UI test depend on JSONPlaceholder?

Solution

Because it would fail for reasons that have nothing to do with the app: the network of the machine running the test, a change in the data, or the service's request limit. The test launches the app with an argument that makes it use fixed data.

Going deeper

performAccessibilityAudit(for:) accepts the audit types you want to run, and a closure that receives each issue and decides whether to ignore it. Ignoring one is a decision you document next to the test, not a way to turn it green.

UI tests are also the most prone to failing without any code change: waits, animations, the keyboard. That's why the part 4 pyramid has many unit tests and few UI tests.

What to take with you: a UI test and an accessibility audit find problems you don't see; the audit found two here.

Debugging and Performance

The list is slow to respond and you have three suspects. Before you change any code, measure: a hunch about why the app is slow is often wrong, and a fix with no prior measurement leaves you no way to know whether it fixed anything. What follows is which tool to open for each symptom and what each one measures.

An Interface That Doesn't Respond (Hang)

A hang is a period when the main thread doesn't respond: the app doesn't process taps or draw. The main run loop is the loop that handles the main thread's events. Most of Apple's tools start reporting a hang when that loop goes more than 250 milliseconds without responding (the Hangs instrument lets you lower the threshold). Apple says users notice it starting at about 100 milliseconds. For the user, it's the list that doesn't react when tapped.

Which Tool for Which Symptom

SymptomToolWhat it measures
A value isn't what you expectLLDB, the debuggerThe program's state, stopped at a point
A closed screen is still in memoryMemory Graph DebuggerWhich objects exist and who retains them
Memory keeps growingInstruments: Allocations and LeaksAllocations over time and blocks with no owner
The interface stuttersInstruments: Time Profiler (includes Hangs)Where CPU time goes and when the main thread got stuck
Interface code off the main threadMain Thread CheckerCalls to interface APIs from another thread
A value changes "on its own", differently on each runThread SanitizerConcurrent accesses to the same memory without synchronization
The app quits on a user's iPhoneXcode's Organizer, Crashes tab; MetricKitWhere each thread was when it quit, with function names and lines

LLDB: v, p, and po

With the app stopped at a breakpoint (click the line number, to the left of the editor), you type into Xcode's debug console (View › Debug Area › Activate Console). The three commands you'll use most:

(lldb) v todo
(lldb) p todo.title.count
(lldb) po error
  • v (short for frame variable) shows a variable from the current frame (the function the program is stopped in). It compiles nothing: it's fast and has no side effects, but it isn't a full expression evaluator.
  • p is an alias for dwim-print: it shows a variable without compiling if it can, and compiles the expression when it needs to (to call methods or do arithmetic).
  • po does the same, but shows the object's description, the one print would print.

Start with v: if it's enough, you don't run code inside the app while you debug.

Memory Graph

The Debug Memory Graph button (in the debug bar, at the bottom of the editor, with the app running) pauses the app and draws the live objects and the references between them. If a screen you closed is still in the list, the graph shows the chain of strong references that retains it: it's the most direct way to find a retain cycle like the one in the first case.

Instruments

Instruments records the app while you use it and analyzes it with templates; Product › Profile (⌘I) builds the app and opens Instruments so you can pick one. Apple recommends choosing the template by the problem: Allocations and Leaks for memory; Time Profiler for interface responsiveness. The Time Profiler, CPU Profiler, and Hitches templates also include the Hangs instrument. With Xcode 27, debugging and Instruments on a physical device require iOS 17 or later.

When the App Quits on a User's iPhone

Everything above assumes the app runs with Xcode attached. A shipped app doesn't have it: when it quits on a user's iPhone, what remains is a crash report.

  • Where to see them. Window › Organizer, Crashes tab. Apple collects them from TestFlight (Apple's service for handing out test versions before you publish) and the App Store: it shows the ones from users who share diagnostics and usage data, and TestFlight's always. Some terminations don't show up there, such as the system's for high memory use or for a launch that takes too long.
  • Symbolicate. The report holds hexadecimal addresses; symbolicating it means translating them into function names and line numbers in your code. That needs that build's symbols, the dSYM file: in Build Settings, Debug Information Format set to "DWARF with dSYM File". If you include the symbols when you upload the app to App Store Connect, the organizer symbolicates the reports for you.
  • MetricKit, the framework that delivers diagnostics and metrics the system captures on the device: your app gets the metrics for the previous 24 hours at most once a day, and the diagnostic reports immediately since iOS 15.

Logging with Logger

Several of the cases' diagnoses say "log the status code" or "log whether there was a token". You log with Logger, from the OSLog framework: one Logger(subsystem:category:) per area of the app, and for each interpolated value you say whether it's public or private.

The .private value marks data that identifies a person; the system can hide it in the logs. The token, on the other hand, is never logged, at any level.

p3-datos/Sources/DataStorage/Logging.swift
extension Logger {
    /// One logger per area of the app: the category lets you filter the console by area.
    static let session = Logger(subsystem: "dev.example.TaskManager", category: "session")
}
 
/// Records what helps to diagnose, and marks what identifies a person.
/// The token itself is never logged, with any privacy level.
func logSignInFailure(status: Int, email: String) {
    Logger.session.error(
        "sign-in failed: status \(status, privacy: .public), account \(email, privacy: .private)"
    )
}

The messages show up in Xcode's console (⇧⌘Y shows it) while you debug; there you can filter by subsystem and category. The example compiles and runs inside the p3-datos tests.

Main Thread Checker and Thread Sanitizer

Main Thread Checker is on by default in Xcode's development schemes: it warns when code off the main thread calls an interface API that can only be used on it.

Thread Sanitizer (TSan) detects data races while the app runs. You turn it on in Product › Scheme › Edit Scheme…, Run action, Diagnostics tab. It only works on the simulator and on macOS: Apple documents that it can't be used with iOS apps on a device.

Swift 6 mode prevents many races at compile time, but not the ones you hide. This program marks a class as @unchecked Sendable ("trust me, compiler") and modifies it from a thousand iterations in parallel. DispatchQueue.concurrentPerform(iterations:) runs the block that many times, spread across several threads at once, and returns when all of them finish:

p3-calidad/Tsan/Tsan.swift
/// @unchecked Sendable silences the compiler. Thread Sanitizer, at run time, does not.
final class UnsafeCounter: @unchecked Sendable {
    var value = 0
}
 
let counter = UnsafeCounter()
DispatchQueue.concurrentPerform(iterations: 1000) { _ in
    counter.value += 1
}
print(counter.value)

I compiled it on the Mac with swiftc -swift-version 6 -sanitize=thread Tsan.swift, and when it ran TSan gave two reports. From each one I keep only the WARNING line, without the process number (pid=…), which changes on every run:

WARNING: ThreadSanitizer: Swift access race
WARNING: ThreadSanitizer: data race

Each report also includes the two call stacks (the chain of functions that led to each access) that collided, and each one's thread.

See it yourself: inside p3-calidad/Tsan, run swiftc -swift-version 6 -sanitize=thread Tsan.swift -o tsan && ./tsan. You get the same two reports, sometimes repeated (two or four in my three runs), and the number printed at the end was below 1000 (999, 997, and 996): increments were lost.

On Linux (Docker), all three runs printed 1000. A run that loses no increments doesn't prove there's no race: TSan reported it anyway.

Check what you learned. The task list is slow to react when you tap it. Which Instruments template do you open first?

Solution

Time Profiler. It includes the Hangs instrument, which marks when the main thread stopped responding, and shows which functions the time went to during those periods. Only then do you know what to move off the main actor.

Going deeper

the 250-millisecond threshold is the one the tools use for reporting, not a guarantee that below it the user notices nothing. And TSan only sees the races that happened in that run: if a dangerous interleaving didn't happen during the test, it doesn't report it. That's why Swift 6 mode, which rejects them at compile time, and TSan, which looks for them at run time, complement each other.

What to take with you: measure first, then fix, then measure again.

Fifteen Real-World Problems

A user writes "the app freezes" or "it signed me out". Where do you start? Along the same path every time: symptom, cause, diagnosis, fix, and prevention. Here you walk it through fifteen typical iOS app problems. All fifteen are illustrative scenarios: I put them together to teach the pattern; they aren't incidents from a real project.

The code for each fix is a program in p3-problemas, compiled without main-actor default isolation (the interface types have @MainActor written out). Where a program needs to simulate the network, a small actor plays the server and counts the requests.

See it yourself: unzip p3-problemas.zip and, in Terminal, inside the folder, run a case: swiftc -swift-version 6 RetainCycle.swift -o cycle && ./cycle. It prints the same as the case's output block. The title of each code block says which file to compile.

A Screen That's Never Released

Illustrative scenario. You open and close a task's detail screen twenty times, and the app's memory goes up each time.

  • Symptom: memory grows as you navigate, and the cleanup code in deinit never runs.
  • Cause: a retain cycle. The screen holds an object that holds a closure that captures the screen: none of the three reference counts reaches zero (you saw it in part 1).
  • Diagnosis: Memory Graph with the screen already closed: screen → ticker → closure → screen.

Before

p3-problemas/RetainCycle.swift
final class LeakyDetailScreen {
    let ticker = Ticker()
    var ticks = 0
 
    func start() {
        // screen -> ticker -> closure -> screen: nobody's count reaches zero.
        ticker.onTick = { self.ticks += 1 }
    }
 
    deinit { print("deinit LeakyDetailScreen") }
}

After

p3-problemas/RetainCycle.swift
final class DetailScreen {
    let ticker = Ticker()
    var ticks = 0
 
    func start() {
        // weak: the closure does not keep the screen alive.
        ticker.onTick = { [weak self] in self?.ticks += 1 }
    }
 
    deinit { print("deinit DetailScreen") }
}

Output

leaky screen:
closed
fixed screen:
deinit DetailScreen
closed
  • Fix: [weak self] in the closure breaks one edge of the cycle. The leaking version never prints its deinit; the fixed one does.
  • Prevention: be suspicious of every closure that's stored in a property and mentions self. A test can check the release with a weak reference to the screen, which must be nil after closing it.

Check what you learned. If instead of storing it in onTick you passed the closure to a function that runs it and discards it (for example, ticker.tickOnce { self.ticks += 1 }), would you need [weak self]?

Solution

No. Without storing it there's no cycle: the closure retains the screen only while it exists, and it stops existing when it finishes. The cycle appears when the screen, directly or indirectly, stores the closure.

Interface Frozen During Import

Illustrative scenario. When you import a file with thousands of tasks, the screen doesn't respond during the import.

  • Symptom: a hang for as long as the import lasts; the progress indicator doesn't even appear.
  • Cause: parsing the file runs on the main actor. While it works, the main thread doesn't handle taps or draw.
  • Diagnosis: Time Profiler with the Hangs instrument: the stuck period matches the function that parses the lines.

Before

p3-problemas/FrozenImport.swift
@MainActor
final class FrozenImportModel {
    var status = "idle"
 
    func importFile(_ lines: [String]) {
        status = "importing"
        let todos = parseLines(lines) // runs on the main actor: the UI waits for it
        status = "imported \(todos.count)"
    }
}

After

p3-problemas/FrozenImport.swift
/// @concurrent: always runs off the caller's actor, whatever the module's settings.
@concurrent
func parseInBackground(_ lines: [String]) async -> [ImportedTodo] {
    parseLines(lines)
}
 
@MainActor
final class ImportModel {
    var status = "idle"
 
    func importFile(_ lines: [String]) async {
        status = "importing"                         // the UI can show this right away
        let todos = await parseInBackground(lines)   // the main actor is free meanwhile
        status = "imported \(todos.count)"
    }
}

Output

before: imported 5000
after: imported 5000
  • Fix: the heavy work moves to a @concurrent function, like the ones in The Keychain. The view model stays on the main actor: it sets "importing", waits without blocking, and writes the result. Both programs import the same 5000 tasks; what changes is where the parsing runs. The freeze itself is shown by Hangs in the app.
  • Prevention: functions that parse, sort, or transform lots of data are declared @concurrent and take and return Sendable values.

The Same Request Three Times

Illustrative scenario. When the list opens, the server log shows three identical requests to /todos.

  • Symptom: duplicate requests, and the list redraws with each of the three responses.
  • Cause: three triggers (onAppear, .refreshable, and a retry button) call the load, and each call creates its own task.
  • Diagnosis: count the calls to the client, in a test or with a breakpoint that doesn't stop: right-click the breakpoint › Edit Breakpoint…, Action "Log Message", and the "Automatically continue after evaluating actions" checkbox.

Before

p3-problemas/Deduplicate.swift
@MainActor
final class NaiveListModel {
    private(set) var rows: [String] = []
    private(set) var tasks: [Task<Void, Never>] = []
    let loader: TodoLoader
    init(loader: TodoLoader) { self.loader = loader }
 
    /// Called from onAppear, from .refreshable and from a retry button.
    func needsData() {
        tasks.append(Task { rows = await loader.load() }) // a new request every time
    }
}

After

p3-problemas/Deduplicate.swift
@MainActor
final class ListModel {
    private(set) var rows: [String] = []
    private var inFlight: Task<Void, Never>?
    let loader: TodoLoader
    init(loader: TodoLoader) { self.loader = loader }
 
    func needsData() {
        guard inFlight == nil else { return } // one load at a time; extra requests are ignored
        inFlight = Task {
            rows = await loader.load()
            inFlight = nil
        }
    }
 
    func waitForData() async {
        await inFlight?.value
    }
}

Output

naive: 3 requests for data, loader calls: 3
fixed: 3 requests for data, loader calls: 1, rows: 3
  • Fix: the view model keeps the in-flight task (the one that has started and not yet finished). While it exists, a new request is ignored. The guard is synchronous and runs on the main actor, so there's no window between checking and assigning. With .refreshable, which keeps the indicator spinning while its closure runs, you have to wait for the load: .refreshable { model.needsData(); await model.waitForData() }.
  • Prevention: every load that several parts of the interface can trigger goes through a single point with its in-flight task. Exercise 14 in part 2 solves the variant with one task per URL inside an actor.

A Counter That Loses Increments

Illustrative scenario. A thousand tasks add one to a shared counter, and the total doesn't reach a thousand.

  • Symptom: in a target still in Swift 5 mode, a different total on each run.
  • Cause: a data race: several tasks read and write the same variable at once.
  • Diagnosis: in Swift 6 mode, the compiler rejects it before it runs:
errores/DataRace.swift:5:19: error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
 3 |     await withTaskGroup(of: Void.self) { group in
 4 |         for _ in 0..<1000 {
 5 |             group.addTask { count += 1 }
   |                   |               `- note: closure captures reference to mutable var 'count' which remains modifiable by code in the current isolation context
   |                   `- error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
 6 |         }
 7 |     }
 
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingClosureRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-closure-risks-data-race>

The error comes from region-based isolation analysis: the closure sent to another task captures count, which the code that creates it can keep modifying.

p3-problemas/CounterActor.swift
/// The counter's state is protected by the actor: one increment at a time.
actor Counter {
    private(set) var value = 0
    func increment() { value += 1 }
}
 
func countConcurrently() async -> Int {
    let counter = Counter()
    await withTaskGroup(of: Void.self) { group in
        for _ in 0..<1000 {
            group.addTask { await counter.increment() }
        }
    }
    return await counter.value
}
 
print(await countConcurrently())
1000
  • Fix: the state moves into an actor, which handles one increment at a time.
  • Prevention: Swift 6 mode in every target, and @unchecked Sendable only with synchronization you can explain. Whatever gets past the compiler, Thread Sanitizer looks for, as you saw in "Debugging and Performance".

Five 401s at Once

Illustrative scenario. The access token expires while five screens are loading data. All five get a 401, all five ask for a new token, and the authentication server receives five refreshes for a single expiration.

  • Symptom: several refreshes in a row in the authentication server's log, and tokens that change while other requests are still using the previous one.
  • Cause: each request refreshes on its own.
  • Diagnosis: count the calls to the refresh: there must be one.
Five 401s, a single refresh
  1. Screen A calls API: GET /todos with the old token
  2. API replies to Screen A: 401
  3. Screen A calls TokenRefresher (actor): newToken(replacing: old)
  4. TokenRefresher (actor) creates Refresh task: creates the refresh task
  5. Refresh task calls Auth server: POST /token with the refresh token
  6. Screen B calls API: GET /users with the old token
  7. API replies to Screen B: 401
  8. Screen B calls TokenRefresher (actor): newToken(replacing: old)
  9. Auth server replies to Refresh task: new token
  10. Refresh task replies to TokenRefresher (actor): new token
  11. TokenRefresher (actor) replies to Screen A: new token
  12. TokenRefresher (actor) replies to Screen B: new token
  13. Screen A calls API: retry with the new token
  14. API replies to Screen A: 200
  15. Screen B calls API: retry with the new token
  16. API replies to Screen B: 200

Step 16 of 16: 200: two 401s, one refresh, two retries.

  1. Screen A asks for its data with a token that just expired.
  2. The API answers 401: the credential no longer works.
  3. A asks the actor for a new token, saying which one was rejected.
  4. There's no refresh in flight: the actor creates one and stores it.
  5. The task calls the authentication server. The actor is free to serve others while it waits.
  6. Meanwhile, screen B asks for its data with the same expired token.
  7. B gets a 401 too.
  8. B asks for a new token. There's a task in flight: B waits on that same task instead of creating another.
  9. The authentication server answers only once.
  10. The actor stores the new token and clears the in-flight task.
  11. A receives the new token.
  12. B receives the same token, from the same task.
  13. A retries only once.
  14. This time, 200.
  15. B retries only once.
  16. 200: two 401s, one refresh, two retries.
Five requests get a 401; all five ask the TokenRefresher actor, which has a single refresh task in flight; that task gets a new token from the authentication server, and the five requests are retried with it.
Five 401s, a single shared refresh, and five retries.

What this fix doesn't do yet: it only coalesces the refreshes. If the refresh fails, every request gets the error and nobody signs out, and a 403 has no rule of its own. Exercise 19 adds those limits.

p3-problemas/TokenRefresh.swift
/// Every request that gets a 401 asks here for a new token. Only the first one
/// starts a refresh; the rest wait for that same task.
actor TokenRefresher {
    private var token: String
    private var refreshing: Task<String, Error>?
    private let refreshOnServer: @Sendable () async throws -> String
    private(set) var refreshes = 0
 
    init(token: String, refreshOnServer: @escaping @Sendable () async throws -> String) {
        self.token = token
        self.refreshOnServer = refreshOnServer
    }
 
    func currentToken() -> String { token }
 
    /// `rejected` is the token that got the 401.
    func newToken(replacing rejected: String) async throws -> String {
        if token != rejected { return token }                     // someone already refreshed
        if let refreshing { return try await refreshing.value }   // a refresh is in flight: join it
 
        let task = Task { try await refreshOnServer() }
        refreshing = task
        defer { refreshing = nil }
        let fresh = try await task.value
        // after the await: the actor may have run other calls (reentrancy), all of them joined
        token = fresh
        refreshes += 1
        return fresh
    }
}
refreshes: 1, retries: 5
statuses: [200, 200, 200, 200, 200]
  • Fix: an actor with a single refresh task in flight. Whoever arrives while it exists waits on that task. Whoever arrives afterward, with the old token, receives the new one without refreshing: that's why the method takes the rejected token.
  • Prevention: a written policy: on a 401, refresh once and retry once; on a 403, don't refresh; if the refresh fails, sign out. Exercise 19 completes it.

Check what you learned. In newToken(replacing:), why is the token stored after the await and not before?

Solution

Because before the await it doesn't exist: it's what the server returns. What matters is what happens during the wait: the actor is reentrant and serves other calls, which find the task in flight and wait on it. That's why the task is stored in refreshing before the await.

Note: a break halfway through the cases. You're about 64% in, some 115 minutes, and five of the fifteen cases done; the ten that follow are shorter and reuse what you've seen.

Rows Repeated While Scrolling

Illustrative scenario. The list loads 20 tasks at a time when it reaches the end. When you scroll fast, tasks 21 to 40 show up twice.

  • Symptom: duplicate rows: 60 rows for 40 tasks.
  • Cause: the last row appears twice while page 2 is still on its way, and both loads compute "the next one is 2".
  • Diagnosis: log which pages were requested: [1, 2, 2] says it all.

Before

p3-problemas/Pagination.swift
@MainActor
final class NaiveFeed {
    private(set) var ids: [Int] = []
    private var loadedPages = 0
    var tasks: [Task<Void, Never>] = []
    let source: PagedSource
    init(source: PagedSource) { self.source = source }
 
    /// Called by onAppear of the last row. While page 2 loads, the last row can appear again.
    func lastRowAppeared() {
        tasks.append(Task {
            let next = loadedPages + 1      // both calls read 1 and ask for page 2
            let page = await source.page(next)
            ids += page
            loadedPages = next
        })
    }
}

After

p3-problemas/Pagination.swift
@MainActor
final class Feed {
    private(set) var ids: [Int] = []
    private var loadedPages = 0
    private var loading: Task<Void, Never>?
    let source: PagedSource
    init(source: PagedSource) { self.source = source }
 
    func lastRowAppeared() {
        guard loading == nil else { return }  // that page is already on its way
        loading = Task {
            let next = loadedPages + 1
            let page = await source.page(next)
            var seen = Set(ids)
            ids += page.filter { seen.insert($0).inserted } // and never the same id twice
            loadedPages = next
            loading = nil
        }
    }
 
    func waitForPage() async { await loading?.value }
}

Output

naive: pages requested [1, 2, 2], rows 60, unique 40
fixed: pages requested [1, 2], rows 40, ids 1...40, no repeats

The program's fake server holds each response until the program releases it: that way the two loads overlap the same way on every run. In an app, the overlap depends on the speed of the finger and of the network.

  • Fix: a single page in flight, and never the same id twice: seen.insert(id) returns a tuple whose inserted is true only if the id was new, so the filter lets only new ones through. The second protection covers another case: if the server inserts a new task at the top while you paginate by page number, page 2 brings a row that was already on page 1.
  • Prevention: pagination lives in a type with its own guard, not scattered across onAppear. If the server offers a cursor (after=<id>), it's more stable than the page number when items are inserted; choosing between the two is common practice, not a standard.

A Slow List with Images

Illustrative scenario. A list with thumbnails stutters while scrolling, especially when going back up.

  • Symptom: Time Profiler shows the time going to decoding images, and the same image is decoded every time its row comes back on screen.
  • Cause: there's no cache of the decoded result.
  • Diagnosis: count decodes per image.
p3-problemas/ImageCache.swift
/// Decoding is the expensive step; the cache keeps the decoded result in memory.
final class ImageStore {
    private let cache = NSCache<NSNumber, DecodedImage>()
    private(set) var decodes = 0
    let usesCache: Bool
    init(usesCache: Bool) { self.usesCache = usesCache }
 
    func image(for id: Int) -> DecodedImage {
        let key = NSNumber(value: id)
        if usesCache, let cached = cache.object(forKey: key) { return cached }
        decodes += 1                       // stands for "decode the downloaded bytes"
        let image = DecodedImage(id: id)
        cache.setObject(image, forKey: key)
        return image
    }
}
without cache: decodes 2
with cache: decodes 1
  • Fix: the decoded image goes into an NSCache. If the system evicts it, it's decoded again: it's a cache, not a store.
  • Prevention: two more things that don't depend on the cache. Heavy decoding goes off the main actor, as in the import case. And every ForEach row needs a stable identity, the data's id and not its position: with identities that change, SwiftUI treats the row as new and redoes its work.

A Form That Accepts Garbage

Illustrative scenario. Tasks get saved with an empty title and an estimate of "abc" minutes.

  • Symptom: invalid data in the database, and screens that fail later when they show it.
  • Cause: validation only looked at the first field, or didn't exist.
  • Diagnosis: a table of inputs and expected errors, like the program's.
p3-problemas/Validation.swift
struct TaskDraft {
    var title: String
    var estimateMinutes: String // what the user typed
}
 
enum DraftError: String {
    case titleEmpty, titleTooLong, estimateNotANumber, estimateOutOfRange
}
 
/// Every problem at once, so the form can mark every field, not only the first one.
func validate(_ draft: TaskDraft) -> [DraftError] {
    var errors: [DraftError] = []
    let title = draft.title.trimmingCharacters(in: .whitespacesAndNewlines)
    if title.isEmpty { errors.append(.titleEmpty) }
    if title.count > 80 { errors.append(.titleTooLong) }
 
    if let minutes = Int(draft.estimateMinutes.trimmingCharacters(in: .whitespacesAndNewlines)) {
        if !(1...600).contains(minutes) { errors.append(.estimateOutOfRange) }
    } else {
        errors.append(.estimateNotANumber)
    }
    return errors
}
"Buy milk", "15" -> ok
"   ", "abc" -> titleEmpty, estimateNotANumber
81 characters, "0" -> titleTooLong, estimateOutOfRange
"Call the bank", "-5" -> estimateOutOfRange
  • Fix: a pure function that returns all the errors, so every field can be flagged at once. The text is trimmed before validating, and a number that isn't a number is a different error from a number out of range.
  • Prevention: validation is domain logic and gets tested with @Test(arguments:), as in "Tests". The server validates again: the app helps the user, it doesn't protect the database.

The User Shows Up Signed Out

Illustrative scenario. After restoring a backup on a new iPhone, the app asks you to sign in.

  • Symptom: the sign-in screen, even though the user never signed out.
  • Cause: it depends on where the token was. With a …ThisDeviceOnly accessibility, the token doesn't migrate to another device: that's expected. If it was in UserDefaults or in a file, besides being insecure, it's lost with anything that wipes the app's data.
  • Diagnosis: read the store at launch and log whether there was a token, without logging the token.
  • Fix: the SessionManager from "Sessions" already solves it: it reads the Keychain at launch, tells "I don't know yet" (.unknown) apart from "no session" (.anonymous), and when the token is missing it leads to the sign-in screen, instead of sending requests that fail.
  • Prevention: choose the accessibility on purpose and say in the product what happens when you switch phones. A test with an empty store checks the "no session" path.

The Eternal Spinner

Illustrative scenario. With poor coverage, the screen shows the loading indicator forever.

  • Symptom: the indicator never goes away.
  • Cause: the code expected success or a server error, and a transport error (no connection, timeout) didn't change the state.
  • Diagnosis: no real network. The simulator has no airplane mode: it uses the Mac's network, so turn off the Mac's Wi-Fi or use Network Link Conditioner. It comes in the Additional Tools for Xcode package: download it from developer.apple.com/download/all with your Apple ID (or from Xcode › Open Developer Tool › More Developer Tools…), open the disk image (the .dmg file you downloaded, which the Mac opens as if it were a disk), and double-click Network Link Conditioner.prefPane in the Hardware folder. It shows up in System Settings › Network Link Conditioner: pick the "100% Loss" profile and turn it on. It affects the whole Mac, so turn it off when you're done. On a development iPhone it's under Settings › Developer › Network Link Conditioner, or use airplane mode. Then a breakpoint in the catch.
p3-problemas/Timeout.swift
enum LoadFailure: Equatable {
    case timedOut, offline, other
}
 
/// From the transport error to something the screen can say. Never an endless spinner:
/// every error ends the loading state with a message and, if it makes sense, a retry.
func failure(for error: URLError) -> LoadFailure {
    switch error.code {
    case .timedOut: .timedOut
    case .notConnectedToInternet, .networkConnectionLost: .offline
    default: .other
    }
}
 
/// Retry by itself only idempotent methods, and only once.
func shouldRetry(method: String, after failure: LoadFailure, attempt: Int) -> Bool {
    let idempotent: Set = ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]
    return attempt == 1 && idempotent.contains(method) && failure == .timedOut
}
GET timedOut -> retry once
POST timedOut -> show the error
GET offline -> show the error
  • Fix: every error ends the loading state with a message. URLError.timedOut arrives when the request's timeoutInterval expires, which measures inactivity (60 seconds by default), not the total duration. On its own, the app retries only an idempotent method (repeating it leaves the server the same as doing it once: GET, PUT, or DELETE yes; POST no), and once: a repeated POST can create the task twice.
  • Prevention: the loading state is an enum with its failure case, like part 2's LoadState, and a test with a fake client that throws URLError(.timedOut) checks that the screen leaves "loading".

A Burst of 429s

Illustrative scenario. During an import, the API answers 429 Too Many Requests: too many requests in a short time.

  • Symptom: the import fails halfway, and retrying right away makes it worse.
  • Cause: the client ignores the Retry-After header, which says how long to wait. The 429 is defined by RFC 6585, which allows including that header; its format is defined by RFC 9110: seconds, or an HTTP date.
  • Diagnosis: log the response's status code and headers.
p3-problemas/RateLimit.swift
/// The longest the app agrees to wait, whatever the server says (a product decision).
let maxWait: TimeInterval = 60
 
/// Retry-After is a number of seconds (only digits, RFC 9110) or an HTTP date.
/// Simplification: of the three date formats the RFC asks to accept, only the preferred
/// one (IMF-fixdate) is read here.
func retryDelay(_ header: String, now: Date) -> TimeInterval? {
    if header.allSatisfy({ ("0"..."9").contains($0) }), let seconds = UInt(header) { // only digits: rejects "inf", "5.5", "+5", "-5"
        return min(TimeInterval(seconds), maxWait)
    }
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX") // HTTP dates are never localized
    formatter.timeZone = TimeZone(identifier: "GMT")
    formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
    return formatter.date(from: header).map { min(max(0, $0.timeIntervalSince(now)), maxWait) }
}
 
/// Waits are injected: the program records them instead of sleeping.
func send(_ request: () async -> (status: Int, retryAfter: String?),
          now: Date,
          wait: (TimeInterval) async -> Void) async -> Int {
    let first = await request()
    guard first.status == 429 else { return first.status }
    // No usable Retry-After: do not hammer the server; give up and let the user retry.
    guard let header = first.retryAfter, let delay = retryDelay(header, now: now) else { return 429 }
    await wait(delay)
    return await request().status // one retry, not a loop
}
waits: [5], status: 200
Retry-After: Fri, 20 Nov 2026 12:00:05 GMT -> wait 5 s
Retry-After: 86400 -> wait 60 s
Retry-After: inf -> ignored
Retry-After: 5.5 -> ignored
Retry-After: 1e3 -> ignored
Retry-After: +5 -> ignored
Retry-After: -5 -> ignored
  • Fix: read Retry-After, wait that long with a cap, and retry once. The seconds are, according to the RFC, a non-negative integer: UInt rejects inf, 5.5, or 1e3, which TimeInterval(_:) would accept (and with inf the wait would never end). The cap, maxWait, is a product decision: the server doesn't decide how long your screen stays frozen.

    The wait is injected: the program records it instead of sleeping. The HTTP date is parsed with en_US_POSIX and GMT, because it's never localized; the program only parses the preferred format (IMF-fixdate), although the RFC asks you to also accept two obsolete formats. It's a simplification.

  • Prevention: without Retry-After, don't retry in a loop: return the 429 and let the user try again. The rate-limit windows of public sample APIs aren't documented.

No Network at Launch

Illustrative scenario. On a plane, the app opens on an error screen even though it has two hundred tasks stored.

  • Symptom: "Couldn't load" with local data available.
  • Cause: the screen only knows two network outcomes, success or error, and doesn't check what's stored.
  • Diagnosis: no network, by turning off the Mac's Wi-Fi while the simulator runs.

One simplification before the code: the program returns the remote rows to the screen. In a real app, whatever arrives is written to the database, and the screen observes the database.

p3-problemas/Offline.swift
enum ListState: Equatable {
    case loading
    case loaded([TodoRow], notice: String?) // what is saved, and why it may be old
    case failed(String)                     // only when there is nothing to show
}
 
/// The local store is the source of truth; the network only updates it.
func refreshList(local: [TodoRow], fetchRemote: () async throws -> [TodoRow]) async -> ListState {
    do {
        return .loaded(try await fetchRemote(), notice: nil)
    } catch let error as URLError where error.code == .notConnectedToInternet {
        if local.isEmpty { return .failed("You're offline and nothing is saved yet.") }
        return .loaded(local, notice: "You're offline. Showing saved tasks.")
    } catch {
        return local.isEmpty ? .failed("Couldn't load tasks.") : .loaded(local, notice: "Couldn't refresh.")
    }
}
loaded 2 rows, notice: You're offline. Showing saved tasks.
failed: You're offline and nothing is saved yet.
  • Fix: what's stored is the source of truth. Without a connection, the screen shows what's stored with a notice; it only fails if there's nothing to show.
  • Prevention: one test per combination: with network, without network and with data, without network and without data.

Stale Data After Editing Elsewhere

Illustrative scenario. You edit a task on the web and the phone keeps showing the old title, even when you come back to the screen.

  • Symptom: stale data for the whole max-age.
  • Cause: the copy is fresh according to its lifetime, and the app doesn't ask.
  • Diagnosis: compare the copy's time with its max-age, as in "Offline, Caching, and Invalidation".
p3-problemas/StaleCache.swift
struct Cached {
    var title: String
    var etag: String
    var storedAt: Date
}
 
/// Fresh entries are used without asking. Only an explicit refresh (forceRevalidation)
/// revalidates a fresh entry: it costs a 304 when nothing changed.
func title(cache: inout Cached?, server: FakeServer, now: Date,
           maxAge: TimeInterval, forceRevalidation: Bool) -> String {
    if let entry = cache, !forceRevalidation, now.timeIntervalSince(entry.storedAt) <= maxAge {
        return entry.title
    }
    let response = server.get(ifNoneMatch: cache?.etag)
    if response.status == 304, var entry = cache {
        entry.storedAt = now // still valid: it is fresh again
        cache = entry
        return entry.title
    }
    cache = Cached(title: response.title ?? "", etag: response.etag, storedAt: now)
    return response.title ?? ""
}
open: Buy milk
reopen at 60 s: Buy milk
pull to refresh: Buy oat milk
pull again: Buy oat milk
requests: 3
  • Fix: a user action (pull to refresh) revalidates even if the copy is fresh. If nothing changed, it costs a 304 with no body; if it changed, the new data arrives. Three requests in total: the first load, the one that brought the change, and a 304.
  • Prevention: after a write of your own, invalidate the copy of that resource; for other people's changes, also revalidate when coming back to the screen, by calling with forceRevalidation: true. The program deliberately doesn't: its "reopen at 60 s" uses the fresh copy without asking, which is the symptom.

N+1 Requests

Illustrative scenario. The list of 20 tasks shows each one's owner name and is slow to appear, slower the longer it is.

  • Symptom: 21 requests for one screen: 1 for the list and 1 more for each row. That pattern is called N+1.
  • Cause: the owner is requested inside the loop over the rows.
  • Diagnosis: count the requests in one load.

Before

p3-problemas/NPlusOne.swift
func rowsOneByOne(_ api: FakeAPI) async -> [String] {
    var rows: [String] = []
    for todo in await api.todos() {              // 1 request...
        let user = await api.user(todo.userId)   // ...plus 1 per row: N + 1
        rows.append("\(todo.id) · \(user.name)")
    }
    return rows
}

After

p3-problemas/NPlusOne.swift
func rowsInTwoRequests(_ api: FakeAPI) async -> [String] {
    let todos = await api.todos()
    let ids = Array(Set(todos.map(\.userId))).sorted()   // the distinct owners, once
    let users = await api.users(ids)                     // one request for all of them
    let names = Dictionary(uniqueKeysWithValues: users.map { ($0.id, $0.name) })
    return todos.map { "\($0.id) · \(names[$0.userId] ?? "?")" }
}

Output

one by one: 20 rows, requests: 21
batched: 20 rows, requests: 2
same rows: true
  • Fix: collect the distinct owners and request them all at once. The 20 tasks belong to a single user: one request for the list and another for the owners. The rows are the same.
  • Prevention: the same problem exists in the database: reading a relationship row by row. In SwiftData, relationshipKeyPathsForPrefetching brings the relationships in the same query.

A Save That Fails

Illustrative scenario. With the disk full, the user taps Save, the form clears, and the task doesn't show up anywhere.

  • Symptom: the text is lost without an error on screen.
  • Cause: the form clears before knowing whether it was saved, and the error is discarded with try?.
  • Diagnosis: a fake repository that always throws.

Before

p3-problemas/SaveFailure.swift
@MainActor
final class NaiveFormModel {
    var title = ""
    var state = FormState.editing
    let repository: any TaskRepository
    init(repository: any TaskRepository) { self.repository = repository }
 
    func save() async {
        let text = title
        title = ""          // the form is cleared before knowing whether it worked
        state = .saving
        try? await repository.save(title: text) // and the error is thrown away
        state = .saved
    }
}

After

p3-problemas/SaveFailure.swift
@MainActor
final class FormModel {
    var title = ""
    var state = FormState.editing
    let repository: any TaskRepository
    init(repository: any TaskRepository) { self.repository = repository }
 
    func save() async {
        state = .saving
        do {
            try await repository.save(title: title)
            title = ""      // only after it was saved
            state = .saved
        } catch {
            state = .failed("Could not save. Your text is still here.") // the draft is kept
        }
    }
}

Output

naive: state saved, title ""
fixed: state failed("Could not save. Your text is still here."), title "Buy milk"
  • Fix: clear the form only after saving, and show the failure while keeping the draft.
  • Prevention: try? on a write is a decision to discard the error; if you didn't make it on purpose, it's a bug. The test with a repository that throws checks the failure path.

Check what you learned. Of the fifteen cases, which ones are solved with "a single task in flight", and why does it work the same way in all three?

Solution

The same request three times, five 401s at once, and rows repeated while scrolling. In all three, several triggers ask for the same thing before the first response arrives. Storing the ongoing task in an isolated place (the main actor or an actor) and making the others wait on it, or ignore it, turns N jobs into one.

What to take with you: most of the fifteen problems are solved with three ideas: one task in flight, local data as the source of truth, and no swallowed errors.

Native Swift Versus React Native

Why write the app in Swift if React Native lets you write it in TypeScript for iOS and Android at once? It's a fair question, and the answer depends on the team and the product, not on a universal winner. What follows uses only what the React Native team and the Expo team document (Expo being the set of tools and libraries on top of React Native that its documentation recommends), checked on November 19, 2026.

The official figures that exist, such as the charts in the 2022 Hermes announcement, compare JavaScript engines with each other, not React Native with native Swift; that's why there are no figures here.

What React Native Is Today

React Native runs the app's logic in JavaScript and draws with the platform's native views. The piece that connects the two sides changed in recent years:

  • Hermes has been the default JavaScript engine since version 0.70, and it compiles JavaScript to bytecode (code already translated for the engine) before the app ships. Hermes V1 has been the default engine since 0.84 (February 2026).
  • The New Architecture is the replacement for the original asynchronous bridge. It's been on by default since 0.76 (October 2024); the previous architecture was frozen in 0.80, and since 0.82 (October 2025) the new one is the only one: the settings to turn it off are ignored. The old code is being removed gradually, but the compatibility layers stay.
  • The stable version as of November 19, 2026 is 0.88, which adds the SceneDelegate lifecycle (the UIKit scene delegate you saw in part 1) on iOS; Swift Package Manager support is still experimental, and CocoaPods is still supported.

The New Architecture has four parts, and their names appear throughout the documentation:

PieceWhat it does
JSI (JavaScript Interface)Lets JavaScript hold references to C++ objects and call their methods without serializing the data (without turning it into bytes to send it). JavaScript and the native side can communicate synchronously
FabricThe new renderer, the piece that turns what React describes into native views. To wrap a native view (a UIButton, for example) you write a Fabric Native Component
Turbo Native ModulesThe native module system: you start from a typed spec in TypeScript or Flow (a type system for JavaScript), and Codegen generates the native interfaces on every build
BridgelessThe asynchronous bridge is no longer used; compatibility layers remain

A fact that matters for an iOS team: Codegen generates C++ and Objective-C++ (Objective-C that can call C++) for iOS, not Swift. The official guide implements a Turbo Module in a .mm file, and the guide for using Swift asks for a thin Objective-C++ layer between the two because, according to the documentation itself, interoperability between Swift and C++ "is not great".

The path meant for Swift is the Expo Modules API: with it, native modules are written in Swift and Kotlin, and Expo documents that its performance is similar to Turbo Modules because both use JSI. Expo SDK 58 uses React Native 0.88, and since Expo SDK 55 only the New Architecture exists.

On threads, this much is certain: rendering and the commit (assembling the new view tree) happen off the main thread, and mounting the views on screen happens on the UI thread, the only one that touches native views. For high-priority events, the renderer can run the whole process synchronously on the UI thread.

Going deeper

the two official architecture pages disagree on which thread computes layout: the threading-model page (2023) puts it on the JavaScript thread and the render-pipeline page (2024) on a background thread. That's why the text gives no more precision than the above.

The Old Bridge's Trade-off

The original bridge serialized every call and queued it asynchronously. That had an upside, which the React Native team acknowledges: the main thread never blocked waiting for JavaScript. And a downside: it couldn't respond synchronously. JSI allows synchronous calls, which make an immediate interface possible and, for the same reason, make blocking possible. It isn't just "faster": it's a different decision.

What You Decide

If you care about…Native (Swift)React NativeFact that backs it
Using a new iOS SDK API the day it shipsDirect: it's the SDK's own languageYou need a native module, or to wait for someone to publish oneModules are written with Turbo Modules or Expo Modules
A team that already writes TypeScriptYou have to learn Swift and the SDKReuses the language and ReactThe logic runs in JavaScript, with Hermes
Code shared with AndroidWritten twice, or shared some other wayOne codebase for both platformsNative views on both, from JavaScript
Writing native modules in SwiftIt's all SwiftWith Turbo Modules, through Objective-C++; with Expo Modules, in SwiftThe Turbo Modules and Expo Modules guides
An interface made 100% of system componentsSwiftUI and UIKitNative views, through FabricFabric Native Components

No column wins every row. An app that lives on what's new in iOS and is built by an iOS team has good reasons to be native; a two-platform app built by a web team, to be React Native. What isn't a reason is performance figures without measurement, on either side.

Check what you learned. Can you write a Turbo Native Module in Swift alone?

Solution

With the official guide, no: Codegen generates Objective-C++ for iOS, and the Swift guide asks for an Objective-C++ layer between the module and Swift. The way to write only Swift is the Expo Modules API, which also uses JSI.

Going deeper

the "About the New Architecture" page on the React Native site still explains how to turn it off and says the team is working to make it the default, even though it was edited in October 2026. It's out of date: the current state comes from each version's release notes, which are what I cite. It's a good reminder for any comparison between technologies: a date and a primary source for every claim.

What to take with you: native or React Native is decided by the team and the product, with dated facts, not by performance figures nobody measured.

Note: last break before the interview. You're about 80% in, some 145 minutes. If you like, go back first to the cases you found hard.

Interview Questions

The interviewer opens Keychain Lab and asks why the token isn't in UserDefaults. These nine questions, numbered as in the rest of the series, are of that kind. Try to answer before you open the solution.

Question 24. (Junior) Where do you store an access token in an iOS app?

Solution

In the Keychain, with the most restrictive accessibility that works, for example kSecAttrAccessibleWhenUnlockedThisDeviceOnly if it's only used while the app is in the foreground. Never in UserDefaults, which stores unencrypted, nor in the logs: a bearer token can be used by anyone who has it. See "The Keychain".

Question 25. (Mid) Does using UserDefaults require declaring anything in the privacy manifest? Do you need to call synchronize()?

Solution

Yes: it's a required reason API, and the usual reason is CA92.1 (data that only the app itself reads). Since May 1, 2024, App Store Connect rejects an app that uses it without declaring it. synchronize(), no: Apple says it's unnecessary and shouldn't be used. See "Where Data Lives".

Question 26. (Mid) A SwiftData context you created by hand didn't save your changes, and someone suggests fetchLimit = 0 to "fetch everything". What do you say about each? And does a lazy var help load fewer rows?

Solution

What's documented is that autosaveEnabled is false except on the mainContext; in my measurement, a context created off the main actor came out false. If something must be saved, call save(). To fetch everything, nil: that's what's documented, even though 0 returned every row in the measurement.

And no: a lazy var defers computing an in-memory property; how many rows the database returns is decided by the FetchDescriptor. See "SwiftData and Core Data".

Question 27. (Mid) What's the difference between no-cache and no-store? What's a 304?

Solution

no-cache allows storing the response, but requires revalidating it before each use; no-store forbids storing it. A 304 Not Modified is the answer to a revalidation (If-None-Match with your copy's ETag) when the resource didn't change: it has no body and your copy is still good. See "Offline, Caching, and Invalidation".

Question 28. Junior to mid. Swift Testing or XCTest? #expect or #require?

Solution

Swift Testing for new unit tests; XCTest for UI tests (XCUIAutomation) and for code that already has them. #expect records the failure and lets the test continue; #require stops it, and you use it when what follows makes no sense without that condition. See "Tests".

Question 29. (Mid) How do you test an HTTP client without a network?

Solution

By injecting the URLSession and, in tests, passing one whose configuration has, in protocolClasses, a custom URLProtocol that returns stored responses and records the requests. Limitations: the session checks its default protocols first, and it doesn't work with background sessions. See "A Fake Server".

Question 30. Mid to senior. A user says the app "freezes". How do you diagnose it?

Solution

First I reproduce it and measure it: Apple's tools report a hang when the main thread goes more than 250 ms without responding, although users notice it from about 100 ms. Time Profiler, which includes Hangs, tells me what was running at that moment. Main Thread Checker, on by default, warns about interface APIs off the main thread; Thread Sanitizer looks for races, only on the simulator or macOS. Then I move the heavy work off the main actor and measure again. See "Debugging and Performance".

Question 31. (Senior) Five requests get a 401 at the same time. Design the token refresh.

Solution

An actor with a single refresh task in flight: the first request creates it and the others wait on it. The method takes the rejected token, and if the current one is already different, it returns it without refreshing. Each request is retried only once; a 403 doesn't refresh; if the refresh fails, the session is closed, with no loop.

Because the actor is reentrant, the task is stored before the await and the state is checked again afterward. See the five 401s case.

Question 32. (Senior) What changed in React Native with the New Architecture, and what does it mean for an iOS team?

Solution

It's been on by default since 0.76 and the only option since 0.82. It replaces the asynchronous bridge with JSI (synchronous calls, no serialization), with Fabric as the renderer and Turbo Modules generated by Codegen. For iOS, Codegen generates Objective-C++: a module in Swift needs an Objective-C++ layer, except with the Expo Modules API, which allows Swift directly.

No performance figures: there are no official measurements comparing React Native with native Swift. See "Native Swift Versus React Native".

Interview Exercises

You get forty minutes and a package with its tests in red. That's how these five exercises, numbered 16 to 20 as in the rest of the series, are set up. Each one states its level. The solution includes the code I ran, what it prints or what its tests check, common mistakes, how I'd evaluate it in an interview, and a follow-up question.

Exercise 16. An import that neither duplicates nor overwrites (Mid, in Xcode). Write importTodos(_:into:now:), which receives tasks from the API (RemoteTodo: id, title, completed) and saves them as SwiftData TodoItems.

  • Requirements: importing three tasks leaves three rows; importing them again adds none; if the user edited one's title, a new import keeps it; a batch that brings the same id twice inserts it once; the function returns how many it inserted.
  • Constraints: an in-memory container in the tests; a single database query per import, not one per task; don't rely on what @Attribute(.unique) does with a duplicate.
  • Where: open the p3-datos package in Xcode (File › Open… and choose its Package.swift). The file Sources/DataStorage/TodoImporter.swift contains the solution: before you start, replace the body of importTodos with return 0, run the tests with Product › Test (⌘U), and watch the four in TodoImporterTests fail. Write the function until they pass.
Solution
p3-datos/Sources/DataStorage/TodoImporter.swift
/// Imports to-dos without duplicating them and without touching what already exists:
/// an id that is already stored is skipped, even if the remote title is different.
/// Returns how many were inserted.
@discardableResult
func importTodos(_ remote: [RemoteTodo], into context: ModelContext, now: Date) throws -> Int {
    let incomingIDs = remote.map(\.id)
    // ONE fetch for the whole batch, not one per to-do.
    let existing = try context.fetch(FetchDescriptor<TodoItem>(
        predicate: #Predicate { incomingIDs.contains($0.remoteID) }
    ))
    var known = Set(existing.map(\.remoteID))
 
    var inserted = 0
    for todo in remote where !known.contains(todo.id) {
        context.insert(TodoItem(remoteID: todo.id, title: todo.title,
                                isCompleted: todo.completed, updatedAt: now))
        known.insert(todo.id) // the same id twice in one batch is inserted once
        inserted += 1
    }
    try context.save()
    return inserted
}

Explanation. @discardableResult lets you call the function without using the number it returns, without a compiler warning. One query fetches the tasks whose remoteID is in the batch (contains inside the #Predicate); the rest are inserted. The Set also drops an id repeated within the same batch. What already exists isn't touched: the import isn't a sync.

Expected result. The example's four tests pass: importing three gives 3; reimporting returns 0 and there are still 3; with task 1's title edited to "Edited on this phone", reimporting keeps it; a batch with a repeated id inserts 3.

Common mistakes. Inserting everything and trusting the unique attribute: in the SwiftData measurement, the second insert replaced the row and would have overwritten the edit. Running one query per task: with 200 tasks, that's 200 queries.

Evaluation criteria. Idempotency tested; a single query; local edits survive; the container lives as long as the test.

Follow-up question. What if the server deletes a task? The series app doesn't sync; doing so would mean comparing the ids and deciding whether a remote deletion wins over a local edit.

Exercise 17. A cache with a time to live and an injected clock (Mid). Write a generic cache that, for each key, says whether its value is fresh (used without asking), stale (shown and revalidated), or expired (not shown).

  • Requirements: configurable ttl and staleness window; looking up a key that doesn't exist returns nil.
  • Constraints: no sleep and no reading the time with Date() inside the cache: the clock is injected.
Solution
p3-problemas/Ej17TTLCache.swift
enum Freshness: String {
    case fresh    // show it, do not ask the server
    case stale    // show it, and revalidate in the background
    case expired  // too old to show: load before showing
}
 
struct TTLCache<Value> {
    struct Entry {
        let value: Value
        let storedAt: Date
    }
 
    let ttl: TimeInterval        // how long an entry is fresh
    let staleWindow: TimeInterval // how long after that it can still be shown
    let now: () -> Date          // injected clock: the tests decide what time it is
    private var entries: [String: Entry] = [:]
 
    init(ttl: TimeInterval, staleWindow: TimeInterval, now: @escaping () -> Date) {
        self.ttl = ttl
        self.staleWindow = staleWindow
        self.now = now
    }
 
    mutating func store(_ value: Value, for key: String) {
        entries[key] = Entry(value: value, storedAt: now())
    }
 
    func lookup(_ key: String) -> (value: Value, freshness: Freshness)? {
        guard let entry = entries[key] else { return nil }
        let age = now().timeIntervalSince(entry.storedAt)
        if age <= ttl { return (entry.value, .fresh) }
        if age <= ttl + staleWindow { return (entry.value, .stale) }
        return (entry.value, .expired)
    }
}
 
// A clock that only moves when the program says so. No sleep, no Date() inside the cache.
final class FakeClock {
    var current = Date(timeIntervalSince1970: 1_800_000_000)
}
 
let clock = FakeClock()
var cache = TTLCache<String>(ttl: 60, staleWindow: 300, now: { clock.current })
cache.store("3 todos", for: "/todos")
 
for seconds in [30.0, 200.0, 400.0] {
    clock.current = Date(timeIntervalSince1970: 1_800_000_000 + seconds)
    let hit = cache.lookup("/todos")
    print("after \(Int(seconds)) s:", hit.map { "\($0.freshness.rawValue) (\($0.value))" } ?? "miss")
}
print("unknown key:", cache.lookup("/users") == nil ? "miss" : "hit")

Explanation. The age is computed with the injected clock, and two limits classify it. The fake clock is a class with a date the program moves: testing "400 seconds later" doesn't take 400 seconds.

Expected result.

after 30 s: fresh (3 todos)
after 200 s: stale (3 todos)
after 400 s: expired (3 todos)
unknown key: miss

Common mistakes. Reading Date() inside the cache, which makes the test depend on the time of day; using < at one limit and <= at another without deciding it.

Evaluation criteria. Determinism; names that say what the interface does in each state; edges decided on purpose.

Follow-up question. Where does an ETag fit in? In the stale state, the revalidation carries If-None-Match, and a 304 renews the entry's date without downloading the body.

Exercise 18. Parameterized tests for an email validator (Junior/Mid). Write validateEmail(_:), which returns the first problem with an email typed into a form, or nil, and its tests.

  • Requirements: empty, containing spaces, without exactly one @, with no name before the @, and with an invalid domain are distinct errors; leading and trailing spaces are trimmed.
  • Constraints: Swift Testing; one case per argument, not a loop inside a single test.
  • Hint: by default split(separator:) drops empty parts, so "@example.com" would give a single part. split(separator: "@", omittingEmptySubsequences: false) keeps them.
Solution
p3-calidad/Sources/Quality/EmailValidator.swift
enum EmailProblem: Equatable, Sendable {
    case empty
    case containsSpaces
    case needsExactlyOneAt
    case missingName
    case invalidDomain
}
 
/// A form check, not RFC 5322: it rejects what is clearly wrong and lets the server,
/// which sends the confirmation email, have the last word.
func validateEmail(_ raw: String) -> EmailProblem? {
    let email = raw.trimmingCharacters(in: .whitespacesAndNewlines)
    if email.isEmpty { return .empty }
    if email.contains(where: \.isWhitespace) { return .containsSpaces }
 
    let parts = email.split(separator: "@", omittingEmptySubsequences: false)
    guard parts.count == 2 else { return .needsExactlyOneAt }
    let (name, domain) = (parts[0], parts[1])
    if name.isEmpty { return .missingName }
 
    let labels = domain.split(separator: ".", omittingEmptySubsequences: false)
    guard labels.count >= 2, labels.allSatisfy({ !$0.isEmpty }) else { return .invalidDomain }
    return nil
}
p3-calidad/Tests/QualityTests/EmailValidatorTests.swift
struct EmailValidatorTests {
    @Test(arguments: [
        ("ana@example.com", nil),
        ("  ana@example.com\n", nil),           // surrounding spaces are trimmed
        ("", EmailProblem.empty),
        ("ana @example.com", .containsSpaces),
        ("ana@@example.com", .needsExactlyOneAt),
        ("@example.com", .missingName),
        ("ana@example", .invalidDomain),
        ("ana@example.", .invalidDomain),
    ] as [(String, EmailProblem?)])
    func validates(input: String, expected: EmailProblem?) {
        #expect(validateEmail(input) == expected, "input: \(input.debugDescription)")
    }
}

Explanation. split with omittingEmptySubsequences: false keeps the empty parts: that way "@example.com" gives an empty name and "ana@example." an empty domain label. The second argument to #expect is the message shown if it fails.

Expected result. All eight cases pass, each one reported separately.

Common mistakes. A single @Test with a loop: the first failure hides the rest. Trying to validate the whole email standard with a regular expression: what confirms an address is the email the server sends.

Evaluation criteria. Edge cases covered; one error per case with its own name; messages that say which input failed.

Follow-up question. When would you use #require in these tests? When a test needs the result to continue, for example if validateEmail returned a normalized value and you wanted to read its parts.

Exercise 19. Token refresh with limits (Senior). Starting from the TokenRefresher in the five 401s case, write a client that applies the full policy.

  • Requirements: five simultaneous 401s produce a single refresh and five retries; a 403 doesn't refresh; if the refresh fails, every request ends in "signed out", with no second refresh and no loop; each request is retried at most once.
  • Constraints: an actor for the state; async fake servers, no network.
Solution
p3-problemas/Ej19TokenRefresh.swift
enum AuthError: Error { case signedOut }
 
/// One refresh in flight at a time (the TokenRefresher of case 5, with its limits).
actor Refresher {
    private var token: String
    private var refreshing: Task<String, Error>?
    private let refreshOnServer: @Sendable () async throws -> String
    private var signedOut = false
    private(set) var refreshes = 0
 
    init(token: String, refreshOnServer: @escaping @Sendable () async throws -> String) {
        self.token = token
        self.refreshOnServer = refreshOnServer
    }
 
    func current() -> String { token }
 
    func newToken(replacing rejected: String) async throws -> String {
        if signedOut { throw AuthError.signedOut }  // the refresh token was already rejected
        if token != rejected { return token }
        if let refreshing { return try await refreshing.value }
        let task = Task { try await refreshOnServer() }
        refreshing = task
        defer { refreshing = nil }
        refreshes += 1
        do {
            token = try await task.value
        } catch {
            signedOut = true                         // no second refresh with the same refresh token
            throw AuthError.signedOut
        }
        return token
    }
}
 
/// The rules: 401 -> refresh once and retry once; 403 -> no refresh (another token is not
/// more permission); a failed refresh -> signed out, never a loop.
struct AuthorizedClient: Sendable {
    let refresher: Refresher
    let send: @Sendable (_ path: String, _ token: String) async -> Int
 
    func get(_ path: String) async throws -> Int {
        let token = await refresher.current()
        let status = await send(path, token)
        guard status == 401 else { return status }
        let fresh: String
        do { fresh = try await refresher.newToken(replacing: token) } catch { throw AuthError.signedOut }
        let retried = await send(path, fresh)
        if retried == 401 { throw AuthError.signedOut } // the new token was rejected too
        return retried
    }
}

Explanation. The actor adds two things to case 5's: it counts the refresh when it starts, and it remembers that the refresh failed (signedOut) so the second request doesn't launch another one with the same refresh token. The client has a single rule per status code: 401 refreshes and retries once, any other code comes back as is, and a 401 after the retry signs out.

Expected result.

five 401 at once: refreshes 1, results ["200", "200", "200", "200", "200"]
retries with the new token: 5
403: refreshes 0, results ["403"]
refresh rejected: refreshes 1, results ["signedOut", "signedOut"]

Common mistakes. Refreshing on every 401; retrying in a loop while 401s keep coming; refreshing on a 403; storing the new token before the await, when it doesn't exist yet, or the in-flight task after it, when others have already gone through.

Evaluation criteria. A single shared refresh; explicit limits; signed-out as a state, not a stray error; tests for all three scenarios.

Follow-up question. Where do you store the refresh token? In the Keychain, like the access token; and if the server rotates it on every refresh, you store the new one before retrying. Two limits of this solution to discuss: signedOut is never reset (a new sign-in would need another Refresher), and a 401 on the retry signs out that request without marking the actor.

Exercise 20. A paginator that doesn't duplicate and respects a 429 (Senior). Combine the repeated rows case and the 429 case: a paginator that requests pages of 20, never two at once, never the same row twice, and that on a 429 waits as long as Retry-After says.

  • Requirements: two triggers in a row request a single page; ids 1…40 with no repeats; a 5-second wait on Retry-After: 5; Retry-After as an HTTP date too; detect the end.
  • Constraints: the wait and the clock are injected; a fake server.
Solution
p3-problemas/Ej20Paginator.swift
/// Seconds as a non-negative integer, or an IMF-fixdate; capped at `maxWait`.
func retryDelay(_ header: String, now: Date, maxWait: TimeInterval = 60) -> TimeInterval? {
    if header.allSatisfy({ ("0"..."9").contains($0) }), let seconds = UInt(header) {
        return min(TimeInterval(seconds), maxWait)
    }
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.timeZone = TimeZone(identifier: "GMT")
    formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
    return formatter.date(from: header).map { min(max(0, $0.timeIntervalSince(now)), maxWait) }
}
 
@MainActor
final class Paginator {
    private(set) var ids: [Int] = []
    private(set) var waits: [TimeInterval] = []
    private(set) var reachedEnd = false
    private(set) var failedStatus: Int?   // the screen shows an error and a retry button
    private var nextPage = 1
    private var loading: Task<Void, Never>?
    private let fetch: @Sendable (Int) async -> (status: Int, retryAfter: String?, ids: [Int])
    private let sleep: @Sendable (TimeInterval) async -> Void
    private let now: @Sendable () -> Date
 
    init(fetch: @escaping @Sendable (Int) async -> (status: Int, retryAfter: String?, ids: [Int]),
         sleep: @escaping @Sendable (TimeInterval) async -> Void,
         now: @escaping @Sendable () -> Date) {
        self.fetch = fetch
        self.sleep = sleep
        self.now = now
    }
 
    /// Safe to call from every onAppear: one page in flight, never the same page twice.
    func loadMore() {
        guard loading == nil, !reachedEnd else { return }
        loading = Task {
            defer { loading = nil }
            var response = await fetch(nextPage)
            if response.status == 429, let header = response.retryAfter,
               let delay = retryDelay(header, now: now()) {
                waits.append(delay)
                await sleep(delay)
                response = await fetch(nextPage) // one retry; a second 429 waits for the next call
            }
            guard response.status == 200 else {
                failedStatus = response.status // never a silent stop: the UI can show it
                return
            }
            failedStatus = nil
            if response.ids.isEmpty { reachedEnd = true; return }
            var seen = Set(ids)
            ids += response.ids.filter { seen.insert($0).inserted }
            nextPage += 1
        }
    }
 
    func settle() async { await loading?.value }
}

Explanation. The in-flight task is the guard; the Set of ids, the defense against repeated rows. On a 429 it waits and retries the same page once; a second 429 leaves the page for the next trigger. An empty page marks the end, and any other status ends up in failedStatus: the screen shows the error and a retry button, never silence.

Expected result. The fake server answers 429 the first time page 2 is requested, which is why it appears twice in the list; page 3 arrives empty and marks the end:

pages requested: [1, 2, 2, 3]
ids: 1...40 without repeats, waits: [5], end: true, failed: no
Retry-After as a date: 5
Retry-After: inf -> ignored

Common mistakes. Triggering the load from every onAppear without a guard; parsing Retry-After with TimeInterval(_:) (it accepts inf) or without a cap; really sleeping in the test.

Evaluation criteria. Robustness against repeated triggers and rate-limit responses; determinism; a single source of truth for "which page comes next".

Follow-up question. Page number or cursor, if the server inserts rows while the user paginates? With a page number, an insertion at the top shifts the rows and the next page repeats one; a cursor (after=<last id>) doesn't have that problem.

What You Learned

  • Every piece of data has its place according to three questions: whether it's secret, what shape it has, and whether you can get it again. UserDefaults for small settings (unencrypted, with a declared reason in the manifest), files for documents, NSCache and URLCache for whatever can be recomputed or downloaded.
  • A secret goes in the Keychain with the most restrictive accessibility that works, and its calls run off the main actor because they block the thread; errSecDuplicateItem is resolved with an update.
  • SwiftData stores and queries records with @Model, ModelContainer, ModelContext, and FetchDescriptor; the safe moves are calling save(), asking for nil for "no limit", and importing without depending on a unique attribute.
  • A cache is invalidated by time (max-age) or by version (ETag, If-None-Match, and 304); no-cache stores and revalidates, no-store doesn't store; a lazy var isn't a data cache.
  • Unit tests are written with Swift Testing (@Test, #expect, #require) or XCTest (XCTAssertEqual, fulfillment), the network is replaced with a custom URLProtocol and the database with an in-memory container; a UI test with performAccessibilityAudit() found two real contrast problems in Keychain Lab.
  • Every symptom has its tool: LLDB, Memory Graph, Instruments, Main Thread Checker, and Thread Sanitizer, and you measure before you fix.
  • Fifteen real-world problems follow the same path of symptom, cause, diagnosis, fix, and prevention, and three of them are solved with a single task in flight.
  • React Native today runs only on its New Architecture; for an iOS team, what changes most is that its native modules go through Objective-C++, except with Expo Modules.
  • Questions 24 to 32 and exercises 16 to 20 prepare you to defend each of those decisions in an interview.

What's Next

In part 4: build a complete native iOS app with SwiftUI and SwiftData you put it all together in Native Task Manager: from the Xcode template to an app with a list, a validated form, an import from JSONPlaceholder, SwiftData, filters, and tests, step by step and with each step's code to download.

Exercise 16's idempotent import and the UI test with its audit get their full version there.

Before you start it, a question for you: of the fifteen problems, which one have you already run into in an app of your own, and which tool would you have opened first?

Bibliography

All sources were checked on November 19, 2026.