skip to content

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%

answer

  1. what plain throws means for the type
  2. typed throws since Swift 6.0
  3. stored and collected outcomes
  4. bridges in both directions
  5. closure thrown-type inference

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:).

solid answer

~50 s

The callback's `Result<Profile, APIError>` named its error type; `async throws` means `throws(any Error)`, so callers' `catch` blocks see `any Error`. Declaring `func fetchProfile() async throws(APIError) -> Profile` (typed throws, Swift 6.0) keeps it, which pays off inside a module whose callers handle every case and less so for a public API whose failures may grow. After the migration `Result` stops being the transport but keeps three jobs: storing an outcome, such as a view model's last load; collecting per-item outcomes without stopping at the first failure; and serving unmigrated callers through a wrapper that calls the async function and hands them a `Result`. `try result.get()` re-throws a stored failure, and Swift 6.4 adds an async `Result(catching:)`: `await Result { () async throws(APIError) in try await fetchProfile() }`. Without the written thrown type, `Failure` becomes `any Error`.

code

swift · 25 lines
swift
enum APIError: Error { case offline, badStatus(Int) }
struct Profile: Sendable { let name: String }

// New API: throws(APIError) keeps the error type in the signature (Swift 6.0+)
func fetchProfile() async throws(APIError) -> Profile {
    throw .badStatus(503)
}

// A stored outcome is still a Result. Swift 6.4 adds an async init(catching:);
// spell out the closure's thrown type, or Failure is inferred as any Error
func snapshot() async -> Result<Profile, APIError> {
    await Result { () async throws(APIError) in try await fetchProfile() }
}

// The old completion-handler entry point, kept for callers not yet migrated
func loadProfile(completion: @escaping @Sendable (Result<Profile, APIError>) -> Void) {
    Task {
        completion(await snapshot())
    }
}

// A stored Result re-enters throwing code through get()
func cachedName(_ cached: Result<Profile, APIError>) throws(APIError) -> String {
    try cached.get().name
}

go deeper

for a junior

Know that an async throws function replaces the completion handler and that try result.get() turns a stored Result back into a thrown error.

for a middle

Explain that plain throws means throws(any Error), so the migration erases APIError unless the new signature is written as throws(APIError).

for a senior

Plan the migration: typed or untyped errors per API, a compatibility wrapper that still hands old callers Result<Profile, APIError>, and the closure-inference trap in Result(catching:).

for a principal

Weigh typed errors in public signatures against API evolution, and set when the callback entry points are removed.

## What the callback's `Result` encoded A completion-handler API such as `func loadProfile(completion: @escaping (Result<Profile, APIError>) -> Void)` tells its callers three things: the call finishes later, it either produces a `Profile` or fails, and when it fails the error is an **`APIError`**. Callers write an exhaustive `switch` over `.failure(.offline)`, `.failure(.badStatus(let code))` and so on, and the compiler checks it. ## What `async throws` changes Moving to `async` removes the callback, and for most callers that is the whole win: straight-line code, no forgotten or doubled callback, and errors that propagate with `try`. The error type is where migrations slip. A plain `throws` is defined as `throws(any Error)`. So - `func fetchProfile() async throws -> Profile` **erases** `APIError`: a caller's `catch` receives `any Error` and has to cast to recover the cases; - `func fetchProfile() async throws(APIError) -> Profile` **keeps** it. Typed throws arrived in Swift 6.0 (SE-0413). Whether to keep it is a design decision, not a default. The typed-throws proposal recommends untyped `throws` for most code and typed throws where the error set is fixed and callers handle it exhaustively, typically inside one module or package. A public SDK that may later load profiles from a cache or a second backend would have to squeeze those failures into `APIError` or break its signature. The mechanics of typed `catch` clauses belong to the lesson on catching and propagating errors. ## Where `Result` still belongs `async throws` replaces `Result` as the **transport** from callee to caller. It does not replace `Result` as a **value**: - **Stored outcomes.** A view model that remembers how its last load went holds a `Result<Profile, APIError>` in a property and renders from it. - **Collected outcomes.** Loading twenty profiles and showing the ones that worked means keeping `[Result<Profile, APIError>]`; a `throw` inside the loop would abort at the first failure. - **Unmigrated callers.** During the migration, the old `loadProfile(completion:)` can be kept as a thin wrapper over the new async function that hands its callers a `Result`, so both call styles share one implementation. ## Bridging between the two forms | Direction | API | Since | |---|---|---| | stored `Result` to throwing code | `try result.get()`, declared `throws(Failure)` | 5.0 (typed in 6.0) | | synchronous throwing call to `Result` | `Result { try work() }` | 5.0 (generic `Failure` in 6.0) | | `async` throwing call to `Result` | `await Result { try await work() }` | 6.4 (SE-0530) | Before Swift 6.4 the last row did not exist, and the usual workaround was an explicit `do { return .success(try await fetchProfile()) } catch { return .failure(error) }`. Wrapping the legacy callback inside the new async function, and guaranteeing it resumes exactly once, is the continuation material covered with suspension points and continuations. ## Pitfalls during the migration 1. **Closure inference widens the error.** `await Result { try await fetchProfile() }` compiles to a `Result<Profile, any Error>` even when `fetchProfile()` throws `APIError`, because Swift 6.4 infers a closure's thrown type as untyped `throws`. Assigning it to a `Result<Profile, APIError>` fails with *invalid conversion of thrown error type 'any Error' to 'APIError'*. Write the closure type: `() async throws(APIError) in`. 2. **Re-erasing at the wrapper.** A compatibility wrapper that catches into `any Error` hands old callers a different type than they had. Keep the wrapper's `Result` typed with `APIError`. 3. **Keeping two public entry points forever.** The callback wrapper is a migration aid; give it a removal date once its callers have moved. 4. **Losing exhaustiveness silently.** Callers that switched over every `APIError` case lose that check if the new signature is untyped; decide deliberately which errors stay typed. ## A migration order that keeps both sides working 1. Write the `async throws(APIError)` function as the single implementation. 2. Rebuild `loadProfile(completion:)` on top of it, handing callers the same `Result<Profile, APIError>` they had. 3. Move callers one screen at a time; each one trades its `switch` in a closure for `try await` in a `do` block, or keeps a `Result` if it stores the outcome. 4. Delete the callback entry point once nothing calls it. The type that crosses each boundary stays `APIError` throughout, which is what lets the compiler check every step.

  • Before Swift 6.4, how did you turn an async throwing call into a `Result`?
    With an explicit `do`/`catch`: `do { return .success(try await fetchProfile()) } catch { return .failure(error) }`. In a function body that only calls a `throws(APIError)` function, the caught `error` is inferred as `APIError`, so the function can return `Result<Profile, APIError>`. The synchronous `Result(catching:)` takes no `async` closure; Swift 6.4 added the `async` overload (SE-0530).
  • Should a public SDK declare `fetchProfile()` as `async throws(APIError)`?
    Usually not. The typed-throws proposal advises untyped `throws` for most APIs because a typed error constrains evolution: if the SDK later adds a disk cache or a second backend, their failures must be translated into `APIError` or the signature must change, breaking clients that relied on it. Typed throws fits module-internal or package code where callers handle every case.
  • Why keep `[Result<Profile, APIError>]` when loading many profiles?
    A `throw` inside the loop aborts at the first failure and discards the profiles already loaded. Storing one `Result` per item keeps every outcome, so the screen can show the profiles that loaded and mark the ones that failed, each with its own `APIError` case.

  • Marking the new function async throws keeps the APIError type the callback's Result declared.
  • Once the API is async, Result has no remaining use in the codebase.
  • Result(catching:) infers APIError from a typed throwing call inside its closure.
  • A public API declared throws(APIError) can start throwing new error types without breaking callers.

Assumes Swift 6.4; typed throws and the typed Result.get() arrived in Swift 6.0, and the async Result.init(catching:) arrived in Swift 6.4 (SE-0530).