Swift — guard and why?
So i’ve been asked multiple times why and when should I use the?guard?statement?The?guard?statement was first introduced in Swift 2.0.
guard?combines two important concepts in the Swift language, optional wrapping (if you’re not sure what optional wrapping is, I suggest you check my article regarding “Optional Wrapping”?here) and where clause.
So, how can guard help us with optional unwrapping?
Assuming we have a?User?object which contains multiple fields and we need them all to use that object, let’s watch the following code snippet:
We can see?in the code snippet above the horrible thing called?Pyramid of Doom?which is something we dont like to do/see as a developer.
So how can we avoid this horrible?Pyramid of Doom?and what is the entire topic for this article,?guard?, of course, the statement that was given to us back in Swift 2.0 comes to our rescue, so how do we use this?guard?statement?
Well, there are multiple ways we can do, i’ll present some of them here, let’s go back again to our?User?object which contains multiple fields , and we want to use all those fields:
So as we can see in the code snippet above, the horrible pyramid is gone, instead we have multiple clauses with each unwrapping a field of?User?, if the condition is not met and the value cannot be unwrapped we fall into the else clause, in the else clause we print into our console the reason for failing.
Another approach will be to gather all the conditions together, example:
领英推荐
In the snippet above we use one?guard?statement to unwrap all fields together, this is not recommended, if we need to know or have a fallback for each of the fields.
guard vs If statement
It’s important to mention what we can achieve with?guard?we can also achieve with an?if?statement,?guard?makes it easier to read and prevents nesting conditions, example:
In the snippet above we can see a simple?if?condition, the condition checks if the?user.name?field equals John, we can achieve the same thing with the?guard?statement, example:
The snippet above shows an example of?guard, we can see that the?guard?statement forces us to?return?if the condition is not met (in this case if the?user.name?does not equal John), otherwise we can continue because the condition is met.
Important?to mention, that unlike?if?,?guard?wont continue the current scope if the condition is not met, and will?return?inside the?else?clause.
Conclusion
The use of guard statement can make our code more readable and maintainable,?guard?is not always the best solution but more situation dependent.?guard?can help you unwrap needed values that the current scope cannot run without,?guard?has it pros, it improves the code clarity and removes the need for nesting conditions .
for further reading click?here.