typestar

Errors in Swift

Typed throws routed by do, try, and catch.

enum EntryError: Error {
    case missingSailNumber
    case lateEntry(daysLate: Int)
}

func register(boat: String, sail: Int?) throws -> String {
    guard let sail else { throw EntryError.missingSailNumber }
    return "\(boat) registered as #\(sail)"
}

// do/try/catch routes thrown errors to their handlers.
do {
    print(try register(boat: "Kestrel", sail: 207))
    print(try register(boat: "Mystery", sail: nil))
} catch EntryError.missingSailNumber {
    print("Rejected: no sail number on the form")
} catch {
    print("Rejected: \(error)")
}

How it works

  1. enum EntryError: Error declares the failure cases.
  2. throws marks the function; try marks each risky call.
  3. Specific catches come before the catch-all error.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
523
Tokens
113
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 104 seconds.

Type this snippet

Step 1 of 3 in Errors & scope, step 22 of 27 in Language basics.

← Previous Next →

Errors in other languages