Guard operation Swift 2

256 Views Asked by At

I use Swift 2 and Xcode 7.

I would like to know the difference between

if condition { ... } else { ... } 

and

guard ... else ...
3

There are 3 best solutions below

5
On BEST ANSWER

The really big difference is when you are doing an optional binding:

if let x = xOptional {
    if let y = yOptional {
        // ... and now x and y are in scope, _nested_
    }
}

Contrast this:

guard let x = xOptional else {return}
guard let y = yOptional else {return}
// ... and now x and y are in scope _at top level_

For this reason, I often have a succession of multiple guard statements before I get to the meat of the routine.

0
On

Like an if statement, guard executes statements based on a Boolean value of an expression. Unlike an if statement, guard statements only run if the conditions are not met. You can think of guard more like an Assert, but rather than crashing, you can gracefully exit.

Reference and code example here.

0
On

To add to Matt's answer, you can include several conditions in a single guard statement:

guard let x = xOptional, y = yOptional else { return }
// ... and now x and y are in scope _at top level_

In addition to optional binding, a guard condition can test boolean results:

guard x > 0 else { return }

In short, the benefit of the guard statement is to make the early exit apparent at the start of the scope, instead of the condition being buried further down in a nested else statement.