skip to content

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%

answer

  1. one side changes, the other stays
  2. the transform's declared return type
  3. convert the error before chaining
  4. what map does with a Result-returning closure

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.

solid answer

~40 s

Each `Result` transform changes the type on one side and keeps the other side's type. `map` applies a non-throwing closure to the success value and keeps `Failure`; `mapError` applies one to the failure and keeps `Success`; `flatMap` applies a closure that itself returns a `Result` and flattens it. Its transform type is `(Success) -> Result<NewSuccess, Failure>`, so the inner result must share the outer error type. A parser returning `Result<Profile, ParseError>` applied to a `Result<String, APIError>` therefore fails to type-check; write `parse(body).mapError { _ in APIError.invalidBody }` inside the closure. Using `map` there instead compiles but yields `Result<Result<Profile, ParseError>, APIError>`. None of these closures may throw; to call a throwing `decode`, use `Result { try decode(response.get()) }`, which widens the error to `any Error`.

code

swift · 22 lines
swift
enum APIError: Error { case offline, invalidBody }
enum ParseError: Error { case missingField(String) }
struct Profile { let name: String }

func parse(_ body: String) -> Result<Profile, ParseError> {
    body.isEmpty ? .failure(.missingField("name")) : .success(Profile(name: body))
}

let response: Result<String, APIError> = .success("")

// map: the transform cannot fail, so the error type is untouched
let length = response.map(\.count)             // Result<Int, APIError>

// map with a Result-returning transform nests
let nested = response.map(parse)               // Result<Result<Profile, ParseError>, APIError>

// flatMap needs the same Failure type, so convert it with mapError first
let profile = response.flatMap { body in
    parse(body).mapError { _ in APIError.invalidBody }
}                                              // Result<Profile, APIError>

print(length, nested, profile, separator: "\n")

go deeper

for a junior

Know that map changes the success value, mapError changes the error, and flatMap is for a transform that returns its own Result.

for a middle

Explain why flatMap needs the inner and outer Failure types to match, read the compiler's conversion error, and fix it with mapError inside the closure.

for a senior

Decide where a chain should give way to get() and straight-line try code, and design the error translation so lower-layer detail is kept or dropped on purpose.

for a principal

Set a convention for how layers translate errors at their boundaries, so chains stay short and each layer's Failure type means something.

## The four transforms `Result` carries a small, fixed set of transforms. Each one runs its closure on **one case** only and passes the other case through untouched: | Method | Closure it takes | Returns | |---|---|---| | `map` | `(Success) -> NewSuccess` | `Result<NewSuccess, Failure>` | | `mapError` | `(Failure) -> NewFailure` | `Result<Success, NewFailure>` | | `flatMap` | `(Success) -> Result<NewSuccess, Failure>` | `Result<NewSuccess, Failure>` | | `flatMapError` | `(Failure) -> Result<Success, NewFailure>` | `Result<Success, NewFailure>` | The closure only runs on the matching case. `map` on a `.failure` returns the same failure without calling the closure; `mapError` on a `.success` does the same for the value. ## `map` and the nested-Result trap `map` is for transforms that **cannot fail**: `response.map(\.count)` turns a `Result<String, APIError>` into a `Result<Int, APIError>`. If the transform can fail and reports that with its own `Result`, `map` still compiles, but it wraps one `Result` in another: - `response.map(parse)` has type `Result<Result<Profile, ParseError>, APIError>`; - every caller then needs two switches, or two `get()` calls, to reach the profile. That nesting is the signal you wanted `flatMap`. ## Why `flatMap` insists on one `Failure` type `flatMap`'s transform returns `Result<NewSuccess, Failure>`, where `Failure` is the **outer** result's error type. The method has no way to merge two error types: the outcome must be a single `Result` with a single `Failure`, and Swift does not invent an `APIError | ParseError` union. So ```swift let profile = response.flatMap(parse) ``` is rejected in Swift 6.4 with: > cannot convert value of type '(String) -> Result<Profile, ParseError>' to expected argument type '(String) -> Result<Profile, APIError>' The fix is to decide what the combined error is and convert before flattening: 1. Pick the error type the chain should end with, here `APIError`. 2. Inside the `flatMap` closure, call `mapError` on the inner result to translate `ParseError` into an `APIError` case such as `.invalidBody`. 3. The closure now returns `Result<Profile, APIError>`, and `flatMap` flattens it. The translation is also where you decide how much of the inner error to keep: `.invalidBody` discards the field name, while a case like `.invalidBody(ParseError)` would carry it along. ## `mapError` and `flatMapError` - **`mapError`** rewrites the failure and keeps the value. It is the standard way to move a lower layer's error into the vocabulary of the layer above, for example wrapping a `ParseError` or adding context. - **`flatMapError`** returns a whole new `Result` from the failure, so it can **recover**: `r.flatMapError { _ in .success(cachedProfile) }` turns a failed load into a cached value. With the annotation `Result<Profile, Never>`, the compiler then knows no failure is left. ## Throwing code inside a chain None of the four closures may throw. `result.map { try decode($0) }` fails with: > invalid conversion from throwing function of type '(String) throws -> Profile' to non-throwing function type '(String) -> Profile' `Sequence.map` propagates its closure's errors, but `Result.map` does not; a `Result` already has a failure channel and expects you to use it. To call throwing code, leave the chain: - `Result { try decode(response.get()) }`, with a throwing `decode`, runs both steps inside `Result(catching:)`. Because Swift 6.4 infers a closure's thrown type as untyped `throws`, `Failure` becomes `any Error`, and you `mapError` back to a concrete type if callers need one. - Or call `try response.get()` in a throwing function and write ordinary `try` code from there. ## When to chain at all Chains of `map`, `flatMap` and `mapError` read well for two or three short steps over a stored `Result`. For longer pipelines, or anything asynchronous, converting to `throws` with `get()` and writing straight-line `try` code is usually clearer. The general theory of mapping versus flattening wrapped values belongs to the functional-programming lessons; what is specific to Swift here is the fixed `Failure` type and the non-throwing closures. A short checklist when reviewing a chain: - a `Result<Result<…>>` anywhere in an inferred type means a `map` should have been a `flatMap`; - a `mapError` that maps every error to one generic case may be throwing away information the caller needed; - a chain that ends in an immediate `switch` might read better as `try result.get()` inside a `do` block; - a key path such as `\.count` works as the transform because key-path expressions convert to functions, which keeps short chains compact.

  • How do you call a throwing parser in the middle of a `Result` chain?
    Leave the chain: `Result { try decode(response.get()) }` runs both steps inside `Result(catching:)`. The closure throws an `APIError` from `get()` or a `ParseError` from `decode`, and its thrown type is inferred as untyped `throws`, so `Failure` is `any Error`; add `mapError` afterwards if callers need a concrete type. Alternatively, `try response.get()` inside a throwing function and continue with plain `try` code.
  • How does `flatMapError` differ from `mapError`?
    `mapError` can only replace one error with another; the result stays a failure. `flatMapError` returns a whole `Result` from the failure, so it can recover: `load.flatMapError { _ in .success(cachedProfile) }` turns a failed load into a success. Its error type can change too, down to `Never` when every failure is recovered.

  • Result.map's closure can throw, and a thrown error becomes the failure case.
  • flatMap combines two different error types into any Error automatically.
  • mapError runs on success values as well as failures.
  • map with a closure that returns a Result flattens the outcome automatically.