Alertable Errors in Swift ⛔️ by@khfarooq

Alertable Errors in Swift ⛔️

Khawaja Farooq HackerNoon profile picture

Khawaja Farooq

Senior Software Engineer

img source: pexel.com

Error is of vital importance. It can occur while communicating with network, disk read or in a runtime situation. Let’s here it 🔉

‘A value used to report that an error condition occurred and normal functionality was skipped’

-Matt Gallagher, Cocoa with love

Motivation

Recently, I came across a snippet by Ritesh Gupta exhibiting some cool techniques about UIAlertController, explaining how to avoid the boilerplate code using swift extensions.

Dirty Trick 💩

Failing gracefully, is what we want to achieve. Swift provides first-class support for handling error at runtime.

Here’s the trick❗️

Real Life Usage 🌏

Let’s take an example of failing gracefully; So we have an app that tells your age based on your date of birth that you input. That’s lame 😑

We need to come up with some validation rules for DOB. We can cater all of them through our custom error;

So Here’s the deal; basically the idea is to shout whenever you came across an error

do {
let yourAge = try age(from: yearOfBirth)
} catch {
error.alert(with: self)
}

Cool isn’t it? 🙃

Download Example App

Author🙏

Feedback,👏 and stay tuned for more swifty tricks.

Say hello on twitter @khfarooq.

Thanks for reading! 🌟

Tags