0Pricing
Swift Academy · Lesson

Result types — Result<T, Error>

Represent success or failure without throwing using Result . Create results, switch over them, map/flatMap, and bridge to/from throws.

Why Result?

Goal: Use Result<T, Error> to return success or failure explicitly—great for callbacks or APIs that avoid throws.

Creating Result

Create .success(value) or .failure(error) instead of throwing.

enum ParseError: Error { case badInt }
func parseInt(_ s: String) -> Result<Int, Error> {
    if let n = Int(s) { return .success(n) }
    else { return .failure(ParseError.badInt) }
}
print(parseInt("42"))
print(parseInt("nope"))

All lessons in this course

  1. Optional chaining & error handling basics
  2. do/catch & defining errors (enums)
  3. Result types — Result
← Back to Swift Academy