skip to content

Result and Failure Strategy

Result stores success or failure as a value, and asserts and preconditions stop on programmer errors. Interviewers ask when to throw, return nil, return a Result or crash.

on this pageshow

explore

questions

5

In Swift, what does `Result<Success, Failure>` hold, and how does a caller read it with `switch` or `Result.get()`?

level: juniorimportance: must knowfreq 68%

answer

  1. two cases, one generic enum
  2. a constraint on the second parameter
  3. exhaustive switch over both cases
  4. turning it back into a throw
  5. the initializer that goes the other way

basics

~10 s

Result is a standard-library enum with two cases, success(Success) and failure(Failure), where Failure must conform to Error. Callers switch over both cases or call get(), which returns the value or throws the stored error.

solid answer

~40 s

`Result<Success, Failure: Error>` stores the outcome of a failable operation as a value, so it can be handed to a completion handler, kept in a property or put in an array, which a `throws` call cannot do: its error only travels up the call stack. To read it, `switch` over `.success(let value)` and `.failure(let error)`; the switch must be exhaustive, and patterns can match one error case, such as `.failure(.offline)`. `get()` turns it back into throwing code: it returns the success value or throws the failure, and since Swift 6.0 it is declared `throws(Failure)`, so the error keeps its concrete type. The reverse bridge is `Result(catching:)`, which runs a throwing closure and stores whichever outcome it produced. `Failure` must conform to `Error`, so `Result<Int, String>` does not compile.

code

swift · 32 lines
swift
enum APIError: Error {
    case offline
    case badStatus(Int)
}

struct Profile { let name: String }

func loadProfile(completion: (Result<Profile, APIError>) -> Void) {
    completion(.failure(.badStatus(503)))
}

// 1. Switch on the two cases; patterns can reach into the error
loadProfile { result in
    switch result {
    case .success(let profile):
        print("Hello, \(profile.name)")
    case .failure(.offline):
        print("Offline")
    case .failure(.badStatus(let code)):
        print("HTTP \(code)")
    }
}

// 2. Turn a Result back into a throw with get()
func displayName(from result: Result<Profile, APIError>) throws(APIError) -> String {
    try result.get().name
}

// 3. Turn a throwing call into a stored Result with init(catching:)
func readToken() throws -> String { "abc" }
let token = Result { try readToken() }   // Result<String, any Error>
print(token)

go deeper

for a junior

Recall the two cases, that Failure must conform to Error, and the two ways to read one: an exhaustive switch or try result.get().

for a middle

Explain what get() and Result(catching:) convert between, and why a closure passed to Result(catching:) yields any Error unless its thrown type is written out.

for a senior

Show where a Result has to outlive the call, such as stored state, per-item outcomes and callbacks, and why a concrete Failure enum makes switches break loudly when a case is added.

for a principal

Frame Result as one of four failure tools a codebase should use consistently, and say which call sites deserve it instead of throws.

## What `Result` is `Result` is a generic **enum** in the Swift standard library, added in Swift 5.0 (SE-0235). Swift 6.4 declares it as `public enum Result<Success: ~Copyable & ~Escapable, Failure: Error>` with exactly two cases, `success(Success)` and `failure(Failure)`. It stores the outcome of a failable operation **as a value**. That is the whole point of the type. A `throws` function reports failure by propagating an error up the call stack, and the error exists only while it propagates. A `Result` can instead be: - passed to a **completion handler**, the first use SE-0235 lists; - **stored** in a property and inspected later, such as the outcome of the last load; - **collected** in an array, one outcome per item, without stopping at the first failure; - **compared** in a test, because `Result` is `Equatable` when both `Success` and `Failure` are, and `Hashable` on the same terms. The `Failure` parameter is constrained to `Error`. `Result<Int, String>` is rejected with *type 'String' does not conform to protocol 'Error'*. `Result<Int, any Error>` is accepted, because `any Error` is special-cased to conform to `Error` itself; that self-conformance was added as preparation for `Result`. ## Reading it with `switch` A `switch` over a `Result` must be **exhaustive**: it covers `.success` and `.failure`, or ends in a `default`. Because the error is an associated value, a pattern can reach inside it: | Pattern | Matches | |---|---| | `case .success(let profile)` | any success, binding the value | | `case .failure(.offline)` | one specific error case | | `case .failure(.badStatus(let code))` | an error case, binding its payload | | `case .failure(let error)` | any failure, binding the error | When `Failure` is a concrete enum such as `APIError`, listing every error case makes the switch exhaustive with no `default`, and, for an enum declared in your own module, adding a case to `APIError` later turns every such switch into a compile error, which is usually what you want. ## Reading it with `get()` `get()` converts a `Result` back into throwing code: 1. If the value is `.success`, it returns the payload. 2. If the value is `.failure`, it **throws** the payload. It never returns `nil` and never traps. Since Swift 6.0 the declaration is `consuming func get() throws(Failure) -> Success` (typed throws, SE-0413). Before 6.0 it threw `any Error`. The typed form matters in two places: - inside a function declared `throws(APIError)`, `try result.get()` needs no conversion; - for `Result<Int, Never>`, `get()` cannot throw at all, so no `try` is needed. ## Creating one with `init(catching:)` `Result(catching:)` goes the other way: it runs a throwing closure and stores the return value as `.success` or the thrown error as `.failure`. `Result { try readToken() }` is the one-line way to capture the outcome of a throwing call for later. Two details catch people out: - **The closure's thrown type is inferred as untyped `throws`.** Even when `readToken()` is declared `throws(TokenError)`, `Result { try readToken() }` is a `Result<String, any Error>`; Swift 6.4 does not infer typed throws for closures. Write `Result { () throws(TokenError) in try readToken() }` to keep the concrete type. - **A non-throwing closure gives `Failure == Never`.** `Result { 42 }` is a `Result<Int, Never>`. Before Swift 6.0 the initializer existed only where `Failure` was `any Error`. Swift 6.4 also adds an `async` overload (SE-0530), so `await Result { try await load() }` captures an asynchronous call. ## Where it fits `Result` does not replace `throws`. For a direct call, `throws` is shorter and the compiler forces the caller to `try`; a function that returns a `Result` can be called and its value ignored with no more than an unused-result warning. `Result` earns its place where the outcome has to outlive the call: callbacks, stored state and collections of outcomes. The syntax of `do`, `catch` and `try?` belongs to the Swift lesson on catching and propagating errors; this one is about the value that holds an outcome. ## Mistakes that show up in review - **Treating `get()` like `try?`.** `get()` throws; to turn a `Result` into an Optional, write `try? result.get()`, and accept that the error is discarded. - **Choosing `any Error` by reflex.** `Result<Profile, any Error>` compiles, but callers can no longer switch over specific cases without casting. Prefer a concrete error enum when callers are expected to react to individual failures. - **Expecting traps to be caught.** `Result(catching:)` stores only *thrown* errors. An out-of-range index or a failed `precondition` inside the closure still stops the program. - **Switching with `default`.** A `default` branch in a switch over a concrete `Failure` hides new error cases from the compiler; list the cases instead.

  • What type is `Result { try readToken() }` when `readToken()` is declared `throws(TokenError)`?
    `Result<String, any Error>`. Swift 6.4 infers a closure's thrown type as untyped `throws`, so the concrete type is lost, and annotating the variable as `Result<String, TokenError>` does not help: the compiler reports *invalid conversion of thrown error type 'any Error' to 'TokenError'*. Spell the closure's type instead: `Result { () throws(TokenError) in try readToken() }`.
  • When can a test compare two `Result` values with `==`, and when can't it?
    `Result` conforms to `Equatable` only when both `Success` and `Failure` do. A concrete error enum without associated values gets `Equatable` synthesized automatically, so `Result<Profile, APIError>` compares when `Profile` is `Equatable` too. `any Error` is not `Equatable`, so a `Result<Int, any Error>` cannot be compared directly; switch on it or compare the success value instead.

  • Result's Failure can be any type, such as a String message.
  • Result.get() returns nil when the value holds a failure.
  • A switch over a Result can handle only the success case and still compile.
  • Result replaced throws, so new functions should return Result instead of throwing.
  • Result(catching:) also catches traps such as an out-of-range array index.

Assumes Swift 6.4; Result.get() has been throws(Failure) and init(catching:) generic over Failure since Swift 6.0, and the async init(catching:) arrived in Swift 6.4.

open as a page

In Swift, what do `assert`, `precondition` and `fatalError` each do in `-Onone`, `-O` and `-Ounchecked` builds?

level: middleimportance: must knowfreq 62%

basics

~20 s

assert checks only in -Onone (Debug) builds; precondition checks in -Onone and -O, so it traps in Release too; fatalError stops the program in every build. In -Ounchecked, assert and precondition are not evaluated and the optimizer may assume they hold.

open as a page

In Swift, why does `Result.flatMap` reject a transform that fails with a different error type, and how do `map` and `mapError` help?

level: middleimportance: should knowfreq 38%

basics

~20 s

Result.flatMap keeps Failure fixed: its transform must return a Result with the same error type. Convert the inner error with mapError first; map changes only the success value and nests a transform that returns a Result.

open as a page

Migrating a Swift completion-handler API that delivers `Result<Profile, APIError>` to `async throws`, what happens to the error type, and where does `Result` still belong?

level: seniorimportance: should knowfreq 48%

basics

~20 s

A plain async throws signature erases APIError to any Error; write async throws(APIError), available since Swift 6.0, to keep it. Result remains for stored or collected outcomes and old callback entry points, bridged by get() and init(catching:).

open as a page

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%

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.

open as a page