← Back to Swift Course | Chapter 11: Error Handling | Lesson 3 of 6

The Result Type

Result is a special box that always holds one of two things: either a success with a value inside, or a failure with an error inside.

Creating and Switching on a Result

A Result<Success, Failure> value is created as either .success or .failure, and handled with a switch that binds each case's associated value.

Example: Creating and Switching on a Result

markup
enum MathError: Error {
    case divideByZero
}
func divide(_ a: Int, by b: Int) -> Result<Int, MathError> {
    if b == 0 {
        return .failure(.divideByZero)
    }
    return .success(a / b)
}
let result = divide(10, by: 2)
switch result {
case .success(let value):
    print("Result: \(value)")
case .failure(let error):
    print("Error: \(error)")
}

Converting a Result to a Throwing Call

Result provides a .get() method that converts it back into a throwing expression, bridging the two error-handling styles.

Example: Converting a Result to a Throwing Call

markup
enum MathError: Error {
    case divideByZero
}
func divide(_ a: Int, by b: Int) -> Result<Int, MathError> {
    b == 0 ? .failure(.divideByZero) : .success(a / b)
}
do {
    let value = try divide(9, by: 0).get()
    print(value)
} catch {
    print("Caught via get(): \(error)")
}
Common Mistakes
  1. Forgetting Result requires two generic types -- the success type and the failure (error) type -- both specified in its declaration.
  2. Using switch on a Result but forgetting each case binds its own associated value (.success(let value) / .failure(let error)).
  3. Choosing Result for a function's return type when a simple throws function would be simpler for synchronous code -- Result shines more for storing or passing outcomes around, especially in async callbacks.
Chapter Summary
  • Result<Success, Failure> represents either .success(value) or .failure(error).
  • It's especially useful for representing outcomes that need to be stored or passed around, not just handled immediately.
  • switch is the natural way to handle both cases of a Result.
  • Result requires its Failure type to conform to Error.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.