Get Your Bearings, Clean Up Your Code, Apply Guards.
Keeping track of the scope of where you are and what values and functions you have access to in your Swift code can be pretty tricky, and with the heavy use of optionals in Swift, handling these optional cases can be overwhelming and you can get lost in your code pretty easily. A solution is to use guard statements to make your code neater and avoid indentations in the case of handling optionals.
Hold on, What Are Guard Statements?
A guard statement is a statement in swift used to make the code perform a check. If this check is met, the code is continued inside the scope, but if the condition is not met, it transfers the code out of the scope(it fails gracefully). You can set any conditions you like to the guard statement.
Here it is:
One way to look at this is like, you have a gate, and the gate will turn people away politely if the people don’t meet the condition.
Why Use It?
Now why use guards at all? Isn’t this just like an if statement? Why not use the if else statements to check nil or handle optionals? why add more syntax to your vocabulary? Won’t first time coders be overwhelmed by the guard statement?
Sure it’s a new syntax you’ll have to get used to, but rest assured, the guard statement is a good tool to put in your toolbox of code hullaballoo. Why? 2 reasons, it makes your code more readable, and it actually unwraps optionals for you to use in your code.
“Unwraps optionals? I can use the if let statement for that, no need to learn a new syntax” see, overuse of optional binding using if statements can cause the Pyramid of Doom. Meaning the code gets embedded inside multiple levels of if statements, indentations, and brackets that in the end, resembles a pyramid, and (for me, personally) gets you lost inside your own code.
The existence of optionals means swift has more safety checks and boilerplate to safely run your code, this means more if checks and brackets, and you run into the pyramid of doom multiple times. Using guard statements means you don’t run into these as often, and anyone who reads your code won’t get confused of the scope of certain sections of code, and instead of a pyramid, your code looks more like a series of gates, very clear and clean. Now for me, that just solidifies it, guard statements are awesome.
Okay, let’s try out guard statements to parse through a dictionary, a minefield of optionals and nils that can get confusing fast if you don’t structure your code accordingly. This is the first code that we wrote without the use of guard statements and using if let optional binding to get the data.
It can get pretty confusing, pretty fast. Now let’s try using guards statements.
Clean, like a series of gates, fun to read.
Conclusion: Guards make your code look better and clearer, at the small cost of learning a new syntax.
Now… Guard away!