Alien13 Alien13 - 10 months ago 57
Swift Question

Using guard keyword

I have encountered numerous situations where a coder have used the guard keyword. And then later, in a seemingly almost identical situation the same coder in the same code does not use the guard keyword. I am aware that this may be a stupid question, so please don't bash it. When should I use the guard keyword and where shouldn't I?

Here is an example (there are many more). This is part of a script that is requesting data form an API.

//Here I am using guard
guard let json = json else {

//Now I am not using guard
if let error = error {
} else {
//Error handling

Why not use the:

if let var1 = var1 {
//Keep on going
} else {
//Don't crash

syntax all the time instead of the guard syntax? At first glance it even seems to have more functionality, but I am certain that does not have to be the case.


One great benefit of the guard statement is that you know that if the condition is not satisfied then the execution flow gets stopped.

This is important for several reasons


You can define unwrapped values which don't need a new scope { ... } to be available

func next(num:Int?) -> Int? {
    guard let num = num else { return nil }
    return num + 1


When you read the code you know that if the guard condition is not satisfied then the following lines won't be executed.


You know a guard statement is there to check conditions required for the following block of code.

But I can replace every guard with an if

Sure. We could also replace every while and for with a goto in some languages. And we could always replace recursion with iteration (and viceversa). But this doesn't necessarily means it is always a good idea.

Despite we can implement some behaviours with more then one programming "tool", we should still use the one that better fits that specific scenario.