A better error handling future for iOS with Swift

Update: I now handle errors from callbacks with the Bolts Framework. Consider this article deprecated.


Pattern matching is a fantastic mechanism found in functional programming languages, and Swift has it! Below, we’ll find out how to use it to encapsulate errors in asynchronous code.

Swift Enumerations

Define different cases, resulting in new classes scoped to the enum.

enum GoogleGeocoderResponse {
    case Response(MFLocation)
    case Error(NSError)
}

Instantiate one of the enumbs depending on the scenario:

manager.GET(baseUrl(), parameters: parameters, success: { (operation: AFHTTPRequestOperation!, response) in
            let location = GoogleGeocoder.fromResponse(response!)
            callback(GoogleGeocoderResponse.Response(location))
        }) { (operation, error) in
            callback(GoogleGeocoderResponse.Error(error))
        }

Use the switch syntax to perform pattern matching against these enum classes:

GoogleGeocoder.reverse(location.coordinate, callback: { (response: GoogleGeocoderResponse) in
            switch response {
            case .Error(let error):
                NSLog(error.description)
            case .Response(let location):
                NSLog(location.description)
            }

            self.callback(response)
        })

One of the benefits to pattern matching is speed. Although one might infer run-time type checking in the switch, it is all mostly done at compile time via polymorphism or some other mechanism.

This does not eliminate the need for NSError. That approach is still recommended when interacting with UIKit, etc.

Check out Swiftlytyping’s post on Swift error handling for a more thorough example with generics.

comments powered by Disqus