Swift + Guard

I prefer to have a simple/minimal workspace so I can avoid the destructions when I work. Who else is doing that? 🙈

Let’s admit it, we all want to write “clean code” that is understandable for any programmer who reads it. Many times as we search for the best solution for our problem we tend to write sloppy code which only we can understand

Writing clean code is not just helping us understand better the structure and the purpose of the code but also it helps the developers who are going to work on the project in the future.

There are many ways that we can organize our projects/code. One of them is the guard statement in Swift. This future in this language has a lot of advantages that I will explain later in the post.

Syntax

According to academics, guard statement definition is: “A construct meant to transfer execution out of scope if one or more conditions are not met.” The syntax is clean and it looks like this:

Let’s dive into the advantages now that we peek into the syntax,

  1. Clean code, it really shows code’s intent
  2. The use case is direct and purposeful
  3. Co-workers and other developers can understand what’s going on with this code.

If you’re into the iOS development for a while now, you remember when you use this if statement with the table views & implement a UITableViewDelegate like explained below:

As you can see this is a solid example of how you implement UITableViewDelegate but. Here’s a Huge but with guard statement the code is more understandable and safer.

Now take a moment and think about all these times you used and if to check a lot of things. I can think of a lot of examples like:

  • Is this username text field filled?
  • Is this password text field filled?
  • Is that boolean true or false?
  • Does the user has internet connectivity?

Final thoughts

I really love guard statement. It was hard to get used to it at the beginning but now I can find a thousand ways that this feature of swift helped me write better — more clean code. I hope you enjoyed reading this post. I would love to know your thoughts on guard statement. Leave them in the responses so we can continue our discussion there.

I would like to thank Tom Fox, and Aryan Kashyap for helping me with a couple of suggestions for the initial draft of this article.

Agisilaos Tsaraboulidis is an iOS Developer & the maker of SoundMemory Rush.

If you enjoyed reading this entry, please hit the 💚 button.

--

--

Tsaraboulidis Agisilaos
The adventures Of An iOS Developer

Co-Founder and CTO @irisapp. prev: iOS eng intern @Microsoft. Makes @soundmemoryrush. Photographer. I like traveling. Nerd. 22.