3.6 Guard Statement

Statement guard

  • used inside an if statement, a loop, or a function
  • code in the else clause runs if the condition is false
  • requires a true condition in order for code to run (like a positive if stmt)
  • optional variables are unwrapped in the scope of the guard
  • must exit via: return – function, continue break – if stmt or loop

Guard in Loop

// in a loop -> 1, 2, 3, -4 isn't positive, 5
let positiveArray = [1, 2, 3, -4, 5]

for pos in positiveArray {
   guard pos >= 0 else {
      print("\(pos) isn't positive")
      continue
   }
   print("\(pos)")
}
  • use break to completely leave the loop

Guard in Function

func greet(person: String?) {
   guard let personName = person else {
      print ("Hey no name")
      return
   }
   print("Hello \(personName)")
}

// -> Hello John
greet(person: "John")
// -> Hey no name
greet(person: nil)

Early Exit in Guard Function

func greetLastName(name: (first: String, last: String?)) -> Int {
   guard name.last != nil else {
      print("Last name required")
      return 0
   }
   return 1
}

// -> Last name required, exit with return 0
greetLastName(name: ("Matt", nil))

Guard stops the Pyramid of Doom

  • POD -> nexted if statements
func sendToServer(name: String, address: String) {
   print("sending stuff")
}

func guardSubmit() {
   guard let name = nameField.text else {
      print("No name to submit")
      return
   }
   guard let address = addressField.text else {
      print("No address to submit")
      return
   }
   sendToServer(name: name, address: address)
}

Pyramid of Doom -> example to avoid

func nonguardSubmit() {
   // pyramid of doom starts here
   if let name = nameField.text {
      if let address = addressField.text {
         sendToServer(name: name, address: address)
      } else {
         print("no address to submit")
      }
   } else {
      print("no name to submit")
   }
}