Error handling basics
suggest changeFunctions in Swift may return values, throw errors, or both:
func value() -> Int { return 1 }
func failing() throws {}
func valueOrError() throws -> Int { return 1 }
Any value which conforms to the Error protocol (including NSError objects) can be thrown as an error. Enumerations provide a convenient way to define custom errors:
enum NetworkError: Error {
// Swift 3 dictates that enum cases should be `lowerCamelCase`
case offline
case serverError(String)
}
An error indicates a non-fatal failure during program execution, and is handled with the specialized control-flow constructs do/catch, throw, and try.
throw NetworkError.offline
func load() throws -> Int {
throw NetworkError.serverError("unavailable")
}
Errors can be caught with do/catch:
do {
let result = try load()
print(result)
} catch {
print(error)
}
Any function which can throw an error must be called using try, try?, or try!:
let optionalResult = try? load() // nil if load throws
let forcedResult = try! load() // traps if load throws
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents