Swift 2 introduced the guard
keyword, which could be used to ensure that various data is configured ready to go. An example I saw on this website demonstrates an submitTapped function:
func submitTapped() {
guard username.text.characters.count > 0 else {
return
}
print("All good")
}
I am wondering if using guard
is any different than doing it the old fashioned way, using an if
condition. Does it give benefits, which you could not get by using a simple check?
Reading this article I noticed great benefits using Guard
Here you can compare the use of guard with an example:
This is the part without guard:
Here you’re putting your desired code within all the conditions
You might not immediately see a problem with this, but you could imagine how confusing it could become if it was nested with numerous conditions that all needed to be met before running your statements
The way to clean this up is to do each of your checks first, and exit if any aren’t met. This allows easy understanding of what conditions will make this function exit.
But now we can use guard and we can see that is possible to resolve some issues:
This same pattern holds true for non-optional values as well:
If you still have any questions you can read the entire article: Swift guard statement.
Wrapping Up
And finally, reading and testing I found that if you use guard to unwrap any optionals,
.
Here the unwrapped value would be available only inside the if block