Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 146 ยท Error Handling

The Result Type

Learn how Swift's Result type stores a success value or an error, how to use map, flatMap, mapError and get(), and when to choose Result over throws.

A function that can fail has to tell its caller about the failure somehow. Swift's main answer is throws: the function throws an error, and the caller uses try and do/catch. That works well when you handle the error right away. But sometimes you want to keep the outcome as a value: store it in an array, send it to another part of the program, or finish the work now and decide later what to do about the failure. For that, Swift has Result.

Result is an ordinary enum from the standard library with exactly two cases: .success carrying a value, and .failure carrying an error. This lesson shows how to create results, take them apart, transform them with map and flatMap, and convert between Result and throws. It builds on error handling, custom errors and enumerations.

What a Result is

Result is generic over two types: the type of the success value and the type of the error. You write it as Result<Success, Failure>. The failure type must conform to the Error protocol. Conceptually the definition is just this:

Swift
enum Result<Success, Failure: Error> {
    case success(Success)
    case failure(Failure)
}

A value of type Result<Int, ParseError> is either "here is an Int" or "here is a ParseError". It is never both and never neither, and the compiler makes sure you deal with each case. Compare that with an optional: Int? can say "no value" but it cannot say why. A Result carries the reason.

Swift A function that returns a Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The function body returns .failure(...) or .success(...). Because the return type is already known, Swift lets you drop the Result prefix. The caller uses a switch with a pattern for each case. If you leave one out, the compiler refuses to build, which is the same exhaustiveness safety you get with any enum (see switch).

Reading a value out: get()

A switch is explicit but wordy. Often you only want the value, and you are happy for a failure to become a thrown error. The get() method does exactly that: it returns the success value, or throws the stored error.

Swift get() turns a Result back into a throwing call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

get() is the bridge from the "error as a value" world back to throws. You will use it often when a library hands you a Result and your own code is written in the try style.

The shorthand try? also works on get() and gives you an optional, discarding the error. That is fine when you do not care why it failed. When you do care, keep the Result or use do/catch.

Transforming a Result: map, mapError and flatMap

Because a Result is a value, you can transform it without unwrapping it. This is the same idea as map on an optional or an array.

  • map changes the success value. A failure passes through untouched.
  • mapError changes the error. A success passes through untouched.
  • flatMap changes the success value using a function that itself returns a Result, so you can chain steps that may each fail.
Swift map, mapError and flatMap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Printing a Result shows success(42) or failure(...), so you can see exactly which case you have.

Notice what the last example needed. flatMap requires the new result to have the same failure type as the original. parse fails with ParseError and validate fails with ValidationError, so we first widened both to plain Error with mapError. That is a common pattern: pick one error type for a pipeline, then convert each step to it.

When a pipeline has several kinds of failure, define one error enum for the whole pipeline with a case per failure, and use mapError to convert each step into it. Callers then only need to handle one type.

Creating a Result from throwing code

Often you start with a function that throws, and you want the outcome as a value. The initializer Result(catching:) runs a throwing closure and captures whatever happens.

Swift Result(catching:) captures a thrown error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Result { try ... } is the trailing-closure form of Result(catching:). With an untyped throws function the failure type becomes plain Error, so you can store any error in it.

You can also go in the other direction. A function that returns Result can be wrapped to look like a throwing one using get(), and Result pairs naturally with try? and optional conversion: try? result.get() gives Int?.

Working with many results

Because results are values, you can collect them in arrays and process them together. Two tasks come up all the time: keep only the good values, or split successes from failures.

Swift Splitting successes and failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The two behaviors are different on purpose. compactMap and the two-list loop are lenient: they carry on and report everything. parseAll is strict: all-or-nothing, and it reports the first problem. Pick the one your program needs.

The failure type must be an Error

The second type parameter must conform to Error. Swift will not let you use a bare String as the failure type. That is a deliberate rule: it keeps all failures in the language compatible with throw, catch and get().

Swift Failure must conform to Error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports main.swift:1:16: error: type 'String' does not conform to protocol 'Error', pointing at the String in the Result<Int, String> return type. The fix is to create a small error type, such as struct StorageError: Error { let message: String }, or an enum with a case per problem.

Result and typed throws

Since Swift 6 you can also say exactly which error a function throws: func load() throws(StorageError) -> Int. That gives you much of what Result<Int, StorageError> gave you, with the convenience of try. See typed throws for details. A useful link between the two: the failure type Never means "cannot fail", so Result<Int, Never> is always a success, which is handy in generic code.

Swift Result with Never as the failure type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Result or throws?

Both express failure, and neither is better everywhere. A practical guide:

  • Use throws for ordinary code that runs now and where the caller handles the problem in the same place. The syntax is lighter, and try marks every call that can fail.
  • Use Result when the outcome must be stored, queued, passed to a completion handler, or combined with others as data.
  • Use Result to cross boundaries that cannot throw, such as an old callback API that gives you (Result<Data, Error>) -> Void.
  • Use optionals when there is exactly one way to fail and the reason does not matter.

New code that uses async/await rarely needs Result for callbacks, because async functions can throw directly. You will still see Result in older libraries and when you want to keep an outcome as data. Later lessons on continuations show how to wrap old callbacks into async functions.

Do not use Result to avoid thinking about errors. A Result that you store and never inspect hides failures just like an empty catch block. Always have a plan for the .failure case.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a Result<Int, ParseError> hold?

    Result is an enum with two cases, success and failure. It stores exactly one of them.
  2. 2. What does result.get() do when the result is a failure?

    get() returns the success value or throws the failure error, so you call it with try.
  3. 3. Which method changes only the error of a Result and leaves a success alone?

    map transforms the success value, flatMap chains a step that returns another Result, and mapError transforms the error.
  4. 4. Why does Result<Int, String> not compile?

    The generic constraint is Failure: Error. A String does not conform, so you wrap the message in your own error type.
  5. 5. What does Result { try divide(10, by: 0) } produce if divide throws?

    Result(catching:) runs the throwing closure and stores either its return value or the error it threw.

Summary

  • Result<Success, Failure> is an enum with .success(value) and .failure(error); Failure must conform to Error.
  • Handle it with switch, or call get() inside try to turn a failure back into a thrown error.
  • map transforms the success, mapError transforms the error, and flatMap chains steps that can also fail (with the same error type).
  • Result { try ... } captures the outcome of throwing code as a value.
  • Arrays of results let you be lenient (collect everything) or strict (stop at the first error).
  • Prefer throws for code that handles errors on the spot; use Result when the outcome has to be kept or passed around as data.

Next: defer and Cleanup