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
enum EntryError: Errordeclares the failure cases.throwsmarks the function;trymarks each risky call.- Specific catches come before the catch-all
error.
Keywords and builtins used here
EntryErrorIntStringcasecatchdoelseenumfuncguardletprintregisterreturnthrowthrowstry
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.
Step 1 of 3 in Errors & scope, step 22 of 27 in Language basics.