-4

I use Swift 2 and Xcode 7.

I would like to know the difference between

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

and

guard ... else ...
David Snabel
  • 9,801
  • 6
  • 21
  • 29
hgcahez
  • 413
  • 6
  • 20
  • 2
    Possible duplicate of [Swift 2 guard keyword](http://stackoverflow.com/q/30791488/4151918) –  Nov 30 '15 at 21:06

3 Answers3

4

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • And see my book for further discussion: http://www.apeth.com/swiftBook/ch05.html#SECguard – matt Nov 30 '15 at 19:55
  • Here's a practical code example: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/80551757899141e786b7f601f3879a7b450923c2/bk2ch02p070filters2/ch15p419filters/MyVignetteFilter.swift – matt Nov 30 '15 at 19:57
  • And another (my code is full of this sort of thing): https://github.com/mattneub/Programming-iOS-Book-Examples/blob/80551757899141e786b7f601f3879a7b450923c2/bk2ch14p653backgroundPlayerAndInterrupter/interrupter/interrupter/AppDelegate.swift – matt Nov 30 '15 at 19:57
  • `guard` also requires a `return`, `break` or something similar to exit the code block in which it occurs, where `if` statements don't. The compiler helps enforce the early-exit convention there. – Brad Larson Nov 30 '15 at 19:58
  • @BradLarson And that is _why_ the binding is in scope at top level: if we get to the next line, we are guaranteed that the condition passed, i.e. we _didn't_ exit early, or we wouldn't be here at all. – matt Nov 30 '15 at 19:59
2

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.

Rashwan L
  • 38,237
  • 7
  • 103
  • 107
0

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.

Community
  • 1
  • 1