This article is a follow up to my previous article Keep things DRY. Back then I used ErrorPresenting protocol with a basic presentError(title: String, message: String) function as an example of protocol extension in Swift. Today I’d like to expand this idea and show you a more advanced error presenting function.

If you have little knowledge on error handling in Swift I recommend looking into the documentation. Here’s a sneak peak:

Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime. In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling. Swift enumerations are particularly well suited to modeling a group of related error conditions, with associated values allowing for additional information about the nature of an error to be communicated.

To start with, we need an enum with a list of errors that we want to use. Let’s begin with errors occuring when communicating with a server. We can name those ApiError :

I recommend having separate enums for different kinds of errors, eg. BluetoothError , NotificationError . That way you know immediately what kind of error you’re dealing with.

In order to make our errors verbose to the user we need a title and a description. Error is an empty protocol and it provides neither of those things. Fortunately, we can create our own protocol conforming to Error ! Let’s call it AppError :

Make sure ApiError conforms to AppError by providing title and description for all errors:

Now that your errors can express themself we can create a presentError function:

Notice that it takes Error as an argument. This means we can pass any Error , but only errors conforming to AppError will show as alert. Rest of them will be conveniently printed out in console for easier debugging.

To avoid duplicating this function in every UIViewController that needs error presenting you can either add it as UIViewController extension or — like I did — implement ErrorPresenting procotol with an extension:

You can read more about this approach in my previous article Keep thinks DRY.

This is just a basic idea of how to present errors in Swift. If you want to take things further you could localize your error description or implement parsing errors from HTTP error codes. All those things will fit neatly in your error enums . Have fun!

Don’t forget to tap and hold 👏 and to follow DaftMobile Blog! You can also find us on Facebook and Twitter.