Functions in Swift may return values, throw errors, or both:
-> Intthrowsthrows-> Int
Any value which conforms to the ErrorType protocol (including NSError objects) can be thrown as an error. Enumerations provide a convenient way to define custom errors:
enum NetworkError: ErrorType {
case Offline
case ServerError(String)
}
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
.
throwsthrowreturnthrow
Errors can be caught with do
/catch
:
dotrycatch
Any function which can throw an error must be called using try
, try?
, or try!
:
dotrycatchthrowstrytry?try!