Swiftly

Swift 5.7 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 unwrapped = name else {
    print("Hello guest!")
    return
  }
  print("Hello \(unwrapped)!")
}
greet(name: "Asma")
greet(name: nil)
// Output: 
// Hello Asma!
// Hello guest!