Back

Error handling in Swift explained

Error handling in Swift explained

Swift allows us to throw, propagate and catch errors across functions. Here we'll take a look at how this works with a few examples.Functions that throws errors.There are several already implemented functions that we use on a daily basis that throws errors. You can see them on Xcode when it contains the keyword throws at the end.

Screen shot of the Xcode IDE displaying a pointer for the keyword throws

To call these functions we need to handle any error that it might throw, as we are going to see later on. We can also implement our own function that throws an error. For that we need to add the keyword throws at the end, like this:

Swfit code snippet that throws error

The error could be anything we like as long as it conforms to the Error protocol.

The Do - Try - Catch syntax

Let's get started by writing a function that opens an image to be converted to Data. The initializer for Data can throw an error. Xcode displaying that the initializer throws an error So Xcode will ask us to use try before calling the initializer.

Xcode asks to use try before calling the initializer

Now we have two options: Use try? and don't handle the error. With this the result would be an optional Implement a Do-Try-Catch to handle the errorUsing optional try We can simply add a try? which will not throw an error but the response would be an optional. If there's an error the result would be nil.

Using optional try

Implementing a Do-Try-Catch

With this syntax we have a successful block and a failure block. The Do Try Catch syntax

Create your own error

You can create your own error Enum that works according to what your application needs. The enum must conform to the Error protocol. This is an example of an error enum for a login feature: Swift code of the Login Error enum

How to propagate an error

Instead of handling the error, our function can throw them by propagating to the function that called our function Swift code function that propagates an error

Some use cases in iOS development

Implementing a login function that throws errors

With the same LoginError enum we can implement a login function that throws different errors. Swift code for a login function that throws an error

And another function catches and handles those errors. We need to implement the last catch is not specific to an error. Swift code that catches an error

JSON parsing

Decoding JSON data for the details of a user. Swift code that decodes a JSON data

Conclusion

Error handling is an essential part of developing apps. Knowing how to do so will greatly improve your ability to work on different user cases and properly handle any error.