skip to content

As a Swift team lead, how would you decide when code should trap, throw, return nil or return a `Result`, for example in a configuration loader?

level: principalimportance: should knowfreq 34%

answer

  1. who can fix the failure
  2. bug versus bad input
  3. one obvious reason versus several
  4. outcomes that must outlive the call
  5. typed throws at module boundaries

basics

~20 s

Trap for programmer errors such as broken invariants; throw for recoverable failures the caller should see; return nil when failure has one obvious cause; return a Result to store or pass an outcome. Keep public APIs on untyped throws by default.

solid answer

~50 s

I sort failures by who can fix them. A bug, such as a broken invariant or an impossible state, is fixed in code, so it traps with `precondition` or `fatalError`; anything arriving from the network, a cache or the user must never trap. A simple failure with one obvious cause, like parsing a port number, returns an Optional. A recoverable failure with several causes the caller should see throws. A `Result` is for outcomes that must outlive the call: a stored last load, per-item outcomes, a callback. For a configuration loader: malformed remote or cached config throws and falls back to defaults; a key that validation already guaranteed is read with `preconditionFailure` on a miss. Typed `throws(E)` stays inside modules whose callers handle every case; public APIs default to untyped `throws`. No app target ships with `-Ounchecked`. I enforce it with review guidelines, lint rules and crash-rate tracking.

code

swift · 33 lines
swift
enum ConfigError: Error {
    case unreadable(path: String)
    case malformedLine(Int)
}

struct AppConfig { var values: [String: String] }

// Simple domain error: one obvious reason, the caller decides on the spot
func port(from text: String) -> Int? {
    Int(text)
}

// Recoverable error: several reasons the caller should see, log and fall back from
func parseConfig(_ text: String) throws -> AppConfig {
    var values: [String: String] = [:]
    for (number, line) in text.split(separator: "\n").enumerated() {
        let parts = line.split(separator: "=", maxSplits: 1)
        guard parts.count == 2 else { throw ConfigError.malformedLine(number + 1) }
        values[String(parts[0])] = String(parts[1])
    }
    return AppConfig(values: values)
}

// Programmer error: validation already guaranteed the key, so a miss is a bug
func requiredValue(_ key: String, in config: AppConfig) -> String {
    guard let value = config.values[key] else {
        preconditionFailure("validated config is missing \(key)")
    }
    return value
}

// Stored outcome: the last load is kept for the settings screen to show
let lastLoad: Result<AppConfig, any Error> = Result { try parseConfig("port=8080") }

go deeper

for a junior

Be able to say which failures are bugs to fix and which are conditions to handle, and name the Swift tool for each.

for a middle

Map Optional, throws, Result and the trapping functions to concrete cases, and explain how precondition and assert behave in Release.

for a senior

Classify every failure in a real loader or service, choose fallbacks for recoverable ones, and defend each trap you keep.

for a principal

Own the written policy: where typed throws may cross module boundaries, which traps are allowed, how they are enforced, and how crash data revises the rule.

## The four tools and what each tells the caller Swift gives a team four ways to report that something went wrong, and each one makes a different promise: | Tool | What the caller learns | Caller must | Typical use | |---|---|---|---| | Return `nil` | it failed, not why | unwrap | one obvious failure reason | | `throws` | why it failed, as an `Error` | `try`, then handle or propagate | recoverable, several reasons | | Return `Result` | why it failed, as a stored value | `switch` or `get()` | outcome kept, passed or collected | | Trap (`precondition`, `fatalError`) | nothing; the process stops | fix the code | programmer error | A policy is mostly about choosing among these **consistently**, so that a reviewer can tell from a signature what kind of failure is possible. ## The categories behind the policy Swift's own error-handling rationale (`docs/ErrorHandlingRationale.md` in the compiler repository) sorts failures into kinds that map onto these tools: - **Simple domain errors**, like parsing a string that is not an integer, are "best modeled with an optional return value". The standard library follows this: `Int("abc")` returns `nil`. - **Recoverable errors**, like file-not-found or a network timeout, are what `throws` was designed for: the caller should consider them and usually propagate them to a point that can report them. - **Logic failures**, like an out-of-bounds index or a force-unwrapped `nil`, are programmer mistakes that "should be handled by fixing the code, not by attempting to recover dynamically". The standard library traps on them, as `removeFirst()` does on an empty array. The rationale also says the kind is often a **conscious decision** of the API author, which is exactly why a team needs a policy rather than a fixed rule. ## Applying it to a configuration loader A configuration loader touches every category, which makes it a good test of the policy: 1. **Remote or cached configuration that fails to download or parse**: a recoverable error. `throws`, log it, fall back to the last good or bundled values. Never trap; a bad server response would otherwise crash every client. 2. **A single setting that may be malformed**, such as a port typed by a user: return `nil` and let the caller substitute a default. 3. **A key the validation step has already guaranteed**: a miss means the validator and the reader disagree, which is a bug. `preconditionFailure` with a message names it in Debug, and the trap stops the app before it runs on corrupted state. 4. **Defaults bundled with the app**: if they are missing or malformed, the build itself is broken. Trapping at launch is defensible here, provided a test loads the bundled file so the failure is caught before release. 5. **The outcome of the last load**, shown on a diagnostics or settings screen: a stored `Result`. ## Typed throws in the policy Typed `throws(E)` (Swift 6.0) is the one place where a team's rule matters for API evolution. The typed-throws proposal recommends untyped `throws` for most code and typed throws in three situations: code that stays inside a module or package where callers always handle the error, generic code that only passes errors through, and constrained environments such as Embedded Swift. A reasonable team rule: - module-internal and package-internal functions may use typed throws when callers switch over the cases; - public APIs use untyped `throws` unless the error set is genuinely closed; - "it only throws one kind of error today" is not a reason on its own, as the proposal warns. ## Enforcing and revisiting the policy - Write the rule into the review checklist with one example per tool, drawn from your own codebase. - Flag `fatalError` and `try!` outside an agreed allowlist with a lint rule, so each new trap is a reviewed decision. - Keep `-Ounchecked` off every app target: it removes `precondition` checks and lets the optimizer assume they hold. - Track the crash-free rate per release; a rising rate of `precondition` traps usually means input is being treated as a bug. ## Where reasonable teams differ Trapping early protects data and produces a crash report with a stack, but every trap is an outage for that user. Some teams shipping to many devices downgrade borderline checks to `assert` plus a logged, thrown error; teams guarding money or persistent data keep more `precondition` calls. Neither is wrong, but the choice should be written down, not rediscovered in each review.

  • When is crashing on bad configuration the right call?
    When the configuration ships inside the app and a test loads it before release, a malformed file is a build defect, and trapping at launch fails fast where the team will see it. When the configuration comes from a server, a cache or the user, trapping turns one bad payload into a crash for every client; throw, log and fall back instead.
  • Why should no app target ship with `-Ounchecked`?
    In `-Ounchecked` your `precondition` and `preconditionFailure` calls stop checking: the optimizer may assume their conditions hold. A violated contract then runs on with undefined behaviour instead of producing a crash report, which is the opposite of what the policy relies on traps for. Any speed gained rarely justifies that.
  • Where does `assert` fit into this failure policy?
    It is for internal consistency checks you want verified during development and testing, especially expensive ones, because `-O` builds do not evaluate them. It is never the only guard on external input, and its condition must have no side effects, since that code disappears from Release builds.

  • Network failures should call fatalError so that they show up in crash reports.
  • Every public API should use typed throws because precise errors are always better.
  • Returning nil is always safer than throwing, because nothing can crash.
  • precondition is stripped from Release builds, so it can never crash users.
  • Result should replace throws everywhere so that the codebase is consistent.

Assumes Swift 6.4; typed throws, which the policy restricts at public boundaries, has been available since Swift 6.0.