Swift - Function guard Keyword

Introduction

guard can check to see if a certain condition holds.

The guard keyword lets you define a test that needs to pass.

If it doesn't pass, a different block of code is run.

If the condition doesn't hold, the code following the guard statement will not be executed:

func doAThing(){ 
    guard 1+1 == 2 else { 
        print("wrong") 
        return 
    } 
    print("here") 
} 

You can use guard to deal with optional variables that have to exist for the code to work.

You can use a guard to unwrap them, making them available to the rest of the function.

Demo

func myMethod(importantVariable: Int?) 
{ 
    guard let importantVariable = importantVariable else 
    { /*from www  .  ja  va  2s.  co m*/
        // we need the variable to exist to continue 
        return 
    } 
    print("doing our important work with \(importantVariable)") 
} 
myMethod(importantVariable: 3) // works as expected 
myMethod(importantVariable: nil) // exits function on the guard statement

Result