A better error handling future for iOS with Swift
30 Sep 2014Update: 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.
Instantiate one of the enumbs depending on the scenario:
Use the switch
syntax to perform pattern matching against these enum classes:
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.