An insurance adjuster uploaded photos of a damaged car from a driveway. The app showed a checkmark beside “Upload failed.” After a retry, the claim held two copies of every photo.

Nothing crashed. A transfer callback, a verification failure, and the retry had each been allowed to set its own flag:

SwiftGitHub
struct UploadFlags {
    var isUploading = false
    var isVerifying = false
    var isComplete = false
    var hasFailed = false
}

Four independent Booleans can hold sixteen combinations. The product described six situations: nothing started, uploading, verifying, done, failed, cancelled. The other ten exist anyway, and the code can reach them. isUploading && isComplete is one late callback away. hasFailed && isVerifying is one missing reset away. Each of those combinations renders something, usually a spinner over a success tick or a Retry button under a progress bar, and each arrives in a bug report that nobody can reproduce, because reaching it takes a precise interleaving of callbacks.

Booleans are fine for facts that really are independent. The trouble is that this model can represent situations the product never defined, so nobody decided what they mean. The authority over what the screen may say is not the last callback to arrive. It is a transition someone wrote down.

Start from what the product can be in

For an upload that the server must verify, the bytes reaching the server is not success. The file might fail a virus scan, a format check, or a quota rule. So the states are:

SwiftGitHub
import Foundation
import Observation

enum UploadState: Equatable, Sendable {
    case idle
    case uploading(attempt: UUID)
    case verifying(attempt: UUID, remoteID: String)
    case succeeded(remoteID: String)
    case failed(attempt: UUID, reason: String)
    case cancelled(attempt: UUID)

    var activeAttempt: UUID? {
        switch self {
        case .uploading(let attempt), .verifying(let attempt, _): attempt
        case .idle, .succeeded, .failed, .cancelled: nil
        }
    }
}

enum UploadEvent: Equatable, Sendable {
    case start(attempt: UUID)
    case transferred(attempt: UUID, remoteID: String)
    case verified(attempt: UUID, remoteID: String)
    case failed(attempt: UUID, reason: String)
    case cancel(attempt: UUID)
}

An enum with associated values does two things the Booleans could not. Only one case holds at a time, so the ten undefined combinations cannot be constructed. And each case carries exactly the data that exists in that situation: there is a remoteID while verifying and after success, and none while uploading, so no code can read a remote ID that has not been assigned yet. The optional properties that would otherwise sit next to the flags (remoteID: String?, error: Error?) disappear, along with every if let that guarded them.

The attempt identifier names one execution. Every event carries it, which is what allows the model to tell a callback from the current attempt apart from one that belongs to an attempt the user already cancelled.

An attempt is different from the business operation. "Upload this document" may take three attempts. If the server must not store the document three times, the three attempts share one idempotency key, which lives with the command and outlasts any attempt. Using one identifier for both concepts works until the first retry.

Make every transition a decision

The reducer is a pure function from the current state and an event to the next state:

SwiftGitHub
func reduce(
    _ state: UploadState,
    _ event: UploadEvent
) -> UploadState {
    switch (state, event) {
    case (.idle, let .start(attempt)),
         (.failed, let .start(attempt)),
         (.cancelled, let .start(attempt)):
        return .uploading(attempt: attempt)

    case let (.uploading(current), .transferred(attempt, remoteID))
        where current == attempt:
        return .verifying(attempt: attempt, remoteID: remoteID)

    case let (.verifying(current, expectedID),
              .verified(attempt, remoteID))
        where current == attempt && expectedID == remoteID:
        return .succeeded(remoteID: remoteID)

    case let (.uploading(current), .failed(attempt, reason))
        where current == attempt:
        return .failed(attempt: attempt, reason: reason)

    case let (.verifying(current, _), .failed(attempt, reason))
        where current == attempt:
        return .failed(attempt: attempt, reason: reason)

    case let (.uploading(current), .cancel(attempt))
        where current == attempt:
        return .cancelled(attempt: attempt)

    case let (.verifying(current, _), .cancel(attempt))
        where current == attempt:
        return .cancelled(attempt: attempt)

    default:
        return state
    }
}

Read it as a list of permissions. A start is accepted from idle, failed, or cancelled, and from nowhere else, so a double tap on the button cannot begin a second upload. A transfer result is accepted only while uploading, and only for the current attempt. A verification is accepted only for the attempt and the remote object the machine is waiting on. Everything else leaves the state as it was.

The default branch is where the Boolean version's bugs used to come from. A completion for a cancelled attempt arrives late, matches no rule, and changes nothing. In production I return a rejection reason alongside the unchanged state and count the rejections. A rejected event is sometimes ordinary network timing, and sometimes it is the first sign that an adapter is sending the wrong thing.

The function starts no network request and cancels nothing. It has no clock, no dependencies, and no await. That is what makes it testable in microseconds and readable in a review.

Effects: who does the work

Something still has to perform the upload. The cleanest arrangement is for the transition itself to say what work it authorizes, as data:

SwiftGitHub
enum UploadEffect: Equatable, Sendable {
    case startTransfer(attempt: UUID)
    case startVerification(attempt: UUID, remoteID: String)
    case cancelWork(attempt: UUID)
}

func step(
    _ state: UploadState,
    _ event: UploadEvent
) -> (state: UploadState, effects: [UploadEffect]) {
    let next = reduce(state, event)
    guard next != state else { return (state, []) }

    switch next {
    case .uploading(let attempt):
        return (next, [.startTransfer(attempt: attempt)])
    case .verifying(let attempt, let remoteID):
        return (next, [.startVerification(attempt: attempt, remoteID: remoteID)])
    case .cancelled(let attempt):
        return (next, [.cancelWork(attempt: attempt)])
    case .failed(let attempt, _):
        return (next, [.cancelWork(attempt: attempt)])
    case .idle, .succeeded:
        return (next, [])
    }
}

step is still pure. Given a state and an event, it returns the new state and a list of effect values, and a test can assert on both. A rejected event produces no effects, so a stale callback cannot start work.

A single owner then executes the effects and feeds the results back in as events:

SwiftGitHub
protocol UploadClient: Sendable {
    func transfer(attempt: UUID) async throws -> String
    func verify(remoteID: String) async throws
}

@MainActor
@Observable
final class UploadController {
    private(set) var state: UploadState = .idle

    private let client: any UploadClient
    private var tasks: [UUID: Task<Void, Never>] = [:]

    init(client: any UploadClient) {
        self.client = client
    }

    func send(_ event: UploadEvent) {
        let result = step(state, event)
        state = result.state
        for effect in result.effects {
            run(effect)
        }
    }

    private func run(_ effect: UploadEffect) {
        switch effect {
        case .startTransfer(let attempt):
            tasks[attempt] = Task { [client] in
                do {
                    let remoteID = try await client.transfer(attempt: attempt)
                    send(.transferred(attempt: attempt, remoteID: remoteID))
                } catch {
                    send(.failed(attempt: attempt, reason: "Transfer failed"))
                }
            }

        case .startVerification(let attempt, let remoteID):
            tasks[attempt] = Task { [client] in
                do {
                    try await client.verify(remoteID: remoteID)
                    send(.verified(attempt: attempt, remoteID: remoteID))
                    tasks[attempt] = nil
                } catch {
                    send(.failed(attempt: attempt, reason: "Verification failed"))
                }
            }

        case .cancelWork(let attempt):
            tasks.removeValue(forKey: attempt)?.cancel()
        }
    }
}

The controller contains no rules. It does not decide whether a completion is still relevant; it reports every completion as an event carrying its attempt, and the reducer decides. That is why the cancellation path needs no special handling. Cancelling the task makes transfer throw, the catch sends .failed for that attempt, and the reducer, already in .cancelled, ignores it.

Two things this structure rules out are worth naming. Effects are never started from a view's body or from onChange of a state value, where they would run again whenever SwiftUI re-evaluates. And no code changes state except through send. Given a log of events, the sequence of states and the work that was authorized can be replayed exactly, which is as close to a flight recorder as an app gets.

Cancelled locally is not undone remotely

.cancelled in this model means the app no longer presents that attempt as active. It makes no claim about the server.

If the cancel arrived while the last bytes were in flight, the server may hold a complete file. If it arrived during verification, the server may go on to accept it. Whether that matters depends on the product. For a profile photo it probably does not. For a payment instruction or a document submitted to a regulator, "Cancelled" on screen while the server proceeds is a serious defect.

When cancellation has a remote meaning, model it truthfully: a cancelling state while the cancel request is outstanding, an acknowledgement event, and a reconciling state when the app must ask the server what actually happened. The state vocabulary should come from the guarantees the product can make. An enum that is tidier than reality tells the user something false.

Retry is a new attempt for the same intent

A retry creates a new attempt ID and therefore a new set of expected callbacks. Anything still arriving from the previous attempt carries the old ID and is rejected.

The server sees it differently. It may have completed the first attempt and failed only to say so. If a duplicate would be harmful, the retry must carry the same idempotency key as the original command, and the server must store the outcome with that key and return it on repetition.

The reducer cannot provide this guarantee. It prevents this process from starting two uploads at once. It knows nothing about the same account on an iPad, or about this app after a crash and relaunch. A local "already uploading" guard is a UI courtesy. Exactly-once effects are enforced where the effect happens.

One enormous machine is the same problem again

The opposite mistake is putting everything into one enum: upload phase, network reachability, whether the sheet is expanded, the color scheme. The number of cases multiplies, and most transitions exist only to copy unrelated fields along.

The test for what belongs together is whether the facts are alternatives or independent. Uploading and verifying are alternatives, so they are cases of one enum. Upload phase and network reachability vary independently, so they are separate values, with the relationship between them written down as a rule: losing the network may schedule a retry of an active attempt, and it never turns .succeeded into .failed.

A machine should make the important transitions obvious. Once it has become a catalog of every UI detail, it hides the domain as effectively as the flags did.

Persist intent, not the enum

It is tempting to make UploadState Codable, write it to disk, and call that recovery. It is not, for two reasons.

A persisted .uploading says what the app believed before it was terminated. After relaunch the truth may be that the server has nothing, has part of the file, or has all of it and sent a response the app never received. The task handle is gone either way. What is needed on disk is the durable command (what to upload, and its idempotency key) and any checkpoint the server protocol supports, such as a resumable upload session ID. On launch the app asks the server and derives the presentation state from the answer.

The second reason is that synthesized Codable output for an enum is a storage format you did not design. Renaming a case or reordering associated values changes it, and the next release cannot read what the last one wrote. Give persisted data its own type with explicit keys and a schema version, and treat changes to it as migrations.

Test sequences, then properties

A transition table is the specification, and each row is a one-line test:

Current stateEventExpected
Uploading ATransferred AVerifying A
Uploading BTransferred AUnchanged
Verifying A for object XVerified A for XSucceeded
Verifying A for object XVerified A for YUnchanged
Cancelled AVerified A (late)Unchanged
Failed AStart BUploading B
Uploading AStart BUnchanged

Then sequences, because most real bugs are interleavings: start, cancel, start again, old completion, new completion, verification failure, retry.

A pure reducer also makes property testing cheap. Instead of choosing cases by hand, generate thousands of random event sequences and assert something that must always hold. For this machine: the state becomes .succeeded only through a matching verification.

SwiftGitHub
struct SeededGenerator: RandomNumberGenerator {
    var state: UInt64

    mutating func next() -> UInt64 {
        state &+= 0x9E37_79B9_7F4A_7C15
        var z = state
        z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
        z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
        return z ^ (z >> 31)
    }
}

func firstInvariantViolation(seed: UInt64, steps: Int) -> [UploadEvent]? {
    var generator = SeededGenerator(state: seed)
    let attempts = [UUID(), UUID(), UUID()]
    let remoteIDs = ["x", "y"]

    var state = UploadState.idle
    var history: [UploadEvent] = []

    for _ in 0..<steps {
        let attempt = attempts.randomElement(using: &generator)!
        let remoteID = remoteIDs.randomElement(using: &generator)!
        let event: UploadEvent = switch Int.random(in: 0..<5, using: &generator) {
        case 0: .start(attempt: attempt)
        case 1: .transferred(attempt: attempt, remoteID: remoteID)
        case 2: .verified(attempt: attempt, remoteID: remoteID)
        case 3: .failed(attempt: attempt, reason: "generated")
        default: .cancel(attempt: attempt)
        }

        let previous = state
        state = reduce(state, event)
        history.append(event)

        if case .succeeded(let succeededID) = state, previous != state {
            guard case let .verifying(current, expectedID) = previous,
                  case let .verified(eventAttempt, eventID) = event,
                  current == eventAttempt,
                  expectedID == eventID,
                  eventID == succeededID else {
                return history
            }
        }
    }
    return nil
}

The generator is seeded, so a failure can be reproduced. When the function returns a history, that history is the test case: the exact sequence of events that broke the invariant, ready to paste into a regression test. Unseeded randomness finds the same bugs and then cannot show them to you again.

None of this replaces integration tests of the adapter. A flawless reducer is no help if the client reports verified when the server said "accepted for processing". The reducer is only as truthful as the events it is given.

What to ask of your own models

  • For each cluster of Booleans, how many combinations exist, and how many did the product define?
  • Which optional properties are only meaningful when some flag is set?
  • Can a callback from a previous attempt change the current state?
  • Where are effects started, and can a re-render start one twice?
  • After a relaunch, what does the app know about an operation that was in flight, and how does it find out the rest?

Explicit state earns its keep by letting you explain three things at any moment: what the application believes, which evidence changed that belief, and who still owns the work. The adjuster never saw the enum. They saw a checkmark that told the truth.

References

If this edition sharpened your next review, you can buy me a coffee.