[Updated] How you can use guards to clean up your ugly if statements in Swift.

Farhan Syed
iOS App Development
1 min readApr 11, 2017

In my last two posts I had shown you an example on how to fetch data from a web API and populate the data into a barebones UITableView.

If you look at the Swift code I written for that post, the code to fetch the data was using a quite bit of guards.

Why?

If you use a lot of nested indents, your code becomes unreadable and messy. Which also makes your code harder to maintain when you want to change or add code.

Basic Example.

Now here’s the same thing with a guards.

Using guards is definitely your preference though it’s hard to deny how clean it can make our code which makes it a lot easier to add in more code later.

Don’t fall into the pyramid of doom!

Any questions or suggestions on future posts please let me know. I’d love to write about what you want to learn!

--

--