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
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)")
}
Login to try C/C++/Java/PHP code in the editor
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
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)")
}
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting
Resultrequires two generic types -- the success type and the failure (error) type -- both specified in its declaration. - Using
switchon aResultbut forgetting each case binds its own associated value (.success(let value)/.failure(let error)). - Choosing
Resultfor a function's return type when a simplethrowsfunction would be simpler for synchronous code --Resultshines 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.
switchis the natural way to handle both cases of aResult.Resultrequires itsFailuretype to conform toError.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: