Search code examples
iosswiftswift2guard-statement

Guard operation Swift 2


I use Swift 2 and Xcode 7.

I would like to know the difference between

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

and

guard ... else ...

Solution

  • 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.