Result and typed throws

Swift language Mid-level Swift 6.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

In Swift 6 you want do { try parse() } catch { ... } where error is statically a ParseError. Which declaration?

Options
Hint 1 of 1

Which feature arrived in Swift 6?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A func parse() throws(ParseError) -> Config

Correct. Typed throws makes the catch variable a ParseError.

Why not the others?
  • B func parse() -> Result<Config, ParseError>. That is typed too, but callers switch on the result instead of using do/catch.
  • C func parse() throws -> Config and cast in catch. The error is any Error; you'd need a cast.
  • D func parse() rethrows -> Config. rethrows only applies to functions that take throwing closures.

30-second answer

Result<Success, Failure> stores either a value or an error, which is useful for callbacks or keeping an outcome for later. Swift 6 adds typed throws: throws(ParseError) declares exactly which error a function can throw, so catch gets a ParseError with no casting. Plain throws (meaning any Error) is still the right default for most APIs.

Practise saying it · 30 s. No recording, just a timer

Explain Result and typed throws.

Say your answer out loud, then check which of these points you covered:

  • Result stores an outcome
  • Typed throws names the error
  • Keep untyped for public APIs

Deep dive

Convert with Result { try work() } and try result.get().

Typed throws suit closed error sets in a module, and embedded or generic code.

Public APIs usually keep untyped throws so new error cases don't break clients.

throws(Never) means a function can't throw.

Common mistakes

  • Using typed throws on every public API.
  • Using Result in async code where throws reads better.

Senior take & follow-ups

Seniors explain when typed throws helps and when it locks an API in.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why keep untyped throws in public APIs?

    Show hint

    Adding an error type later would break source compatibility.

  2. How does rethrows relate to typed throws?

    Show hint

    Typed throws generalizes it: throws(E) with a generic E.

Suggest a fix if something here is wrong or out of date.