Swift 2.0 Error Handling

Swift is a safe language and even though many will swear by Objective-C’s long standing “good practices”, there are some really cool features that came out with Swift 2.0. In particular, the new way to handle errors, or the ability to define your own is insanely cool. This feature is probably one of my favorites… Although there are probably articles on the internet covering this topic, here is another one just in case you wanted to read up on it some more.

I have absolutely no intention of mentioning Objective-C’s @try / @catch as I personally don’t believe they are related outside of the actual syntax being somewhat similar. Unrecoverable errors are useless if you ask me… what good is it to know you have an “unrecoverable error”?

So what is this new way of handling errors then? Let’s just say you can define your own errors and use them when the condition is met. Let’s assume we are writing code to check for a number value 10. If the number passed in for evaluation is greater or lesser than 10, we should throw an error and let the user know.

To begin, we need to define our own error. Let’s call it CustomError. You can do that using enums like so:

Next would be to define a function that performs evaluation and either returns, or throws a CustomError letting us know if the number was too large or too small. Here is how it would look:

The idea here is to find out if the error occurred as soon as possible, hence using “guard > evaluate if true else throw” approach. This is awesome, I mean, think about it… we are interested in finding out if the condition is true as soon as possible and if not, we throw an error immediately.

So how would the implementation of this looks like? Here is the hypothetical scenario.

It is important to mention that you can include tuples when declaring CustomError type like so:

Think about the possibilities… One that comes to mind would be passing the status code from unsuccessful API call in addition to the error description. Very nice indeed.

Here is a snipped from the “real world code” I use in my personal project. Below mentioned function simply tries to derive an access token from a passed in string.

All I can say about Swift evolution is that it has been awesome so far. I favor it over Objective-C just a bit more now :].

Swift 2.0 Error Handling