Lesson 6

Error Handling

Error handling refers to the process of handling error conditions in your app. Swift 2.0 adds new statements that give you the ability to throw, catch, and manipulate runtime errors. Prior to Swift 2.0, if your function wanted to indicate failure, it would do so by returning an Optional variable with a nil value. Errors provide a streamlined solution to the problem of indicating failure within a function and handling the failure.

The ErrorType Protocol

An error can be represented by a class, struct, or enumeration that implements the ErrorType protocol. In most cases, you will use enumerations to represent errors. The following code snippet lists an enumeration called NetworkError that could be used to represent error conditions encountered while making a network request.

enum NetworkError: ErrorType {
    case ResourceNotFound
    case ServerError(httpErrorCode:Int)
    case NetworkTimeout
}

NetworkError could be used to represent three potential scenarios:

  • ResoureNotFound: The URL you were trying to reach couldn't be located.
  • NetworkTimeout: The network request timed out.
  • ServerError: Any other error generated by the server, the HTTP error code will be included as an associated value—httpErrorCode.

Throwing and Catching Errors

To indicate that a function can throw a runtime error, you must add the throws keyword to the end of the function declaration:

func doSomething() throws {
…
}

If your function returns a value, then you must add the throws keyword before ...

Get Swift iOS 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.