Swiftly

Swift references for busy coders

Guard

Guard can be used to reduce indentation on the happy path. In a guard statement, the else branch must transfer control to exit the code block containing the guard statement. This can be done with return, break, continue, or throw.

Simple guard

func divide(x: Int, y: Int) -> Int? {
  guard y != 0 else {
    print("You cannot divide by 0.")
    return nil
  }
  let answer = x / y
  return answer
}
print(divide(x: 5, y: 0))
// Output: 
// You cannot divide by 0.
// nil

Guard let

func greet(name: String?) {
  guard let name else {
    print("Hello guest!")
    return
  }
  print("Hello \(name)!")
}
greet(name: "Asma")
greet(name: nil)
// Output: 
// Hello Asma!
// Hello guest!

guard let name is shorthand for guard let name = name: it unwraps the optional into a constant of the same name. The unwrapped value can also be given a different name, as in guard let unwrapped = name.