1

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 {
            completion(.Failure(error))
        } else {
            //Error handling
        }
        return
    }

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.

Alien13
  • 558
  • 3
  • 8
  • 30

1 Answers1

3

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

Unwrapping

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
}

Readability

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

Semantics

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.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • 1
    Apple notes one of the benefits of guard is that you don't have cascades of nested ifs driving the code off to the right side – Feldur Jul 21 '16 at 01:15