Skip to content

Instantly share code, notes, and snippets.

@iAmWillShepherd
Created June 29, 2022 15:01
Show Gist options
  • Save iAmWillShepherd/4be71c3d4d9fd185a6ec1ae7a1d9dd59 to your computer and use it in GitHub Desktop.
Save iAmWillShepherd/4be71c3d4d9fd185a6ec1ae7a1d9dd59 to your computer and use it in GitHub Desktop.
If statements vs Guard statements
if true {
  print("This statement gets executed when condition is true")
}

vs.

guard true else {
  print("This statement gets executed when condition is true")
}

☝🏾 the if and guard statements are effectlively the same let's see how they are different...

if let value = someOptional {
   // ...
}

print("\(value)") // Error - `value` is only in scope inside the `if` block

vs.

guard let value = someOptional else {
  // ...
  return
}

print("\(value)") // Works - guard clause ensures `value` exists

Guard statements give you a cleaner way to unwrap optionals than If statements since they're kept in scope when the guard condition evaluates to true..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment