Swift - Function guard Keyword


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 { 

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.


func myMethod(importantVariable: Int?) 
    guard let importantVariable = importantVariable else 
    { //from  ww  w.  j  a v a2s  . co  m
        // we need the variable to exist to continue 
    print("doing our important work with \(importantVariable)") 
myMethod(importantVariable: 3) // works as expected 
myMethod(importantVariable: nil) // exits function on the guard statement