Skip to content

Instantly share code, notes, and snippets.

@dry1lud
Last active November 4, 2019 10:41
Show Gist options
  • Save dry1lud/55500b19c53afd76ad1d1ee2b652251a to your computer and use it in GitHub Desktop.
Save dry1lud/55500b19c53afd76ad1d1ee2b652251a to your computer and use it in GitHub Desktop.
Benefits of using a 'guard' statement in Swift language

It forces you to break ealier

  1. It has a positive test rather than negative one
  2. The else clause forces you to bring a program control outside the 'guard' scope (exit the function)
guard let var1 = par1 else { // else is mandatory
   return // must have. brings it outside the scope.
}
```swift
## Unlike the 'if' statement the variables declared at the condition block are visible in the whole 'guard' scope

```swift
guard let var1 = par1 else { // else is mandatory
   return // must have. brings it outside the scope.
}
print(var1)

The condition block supports optional binding and multiple conditions in the same way as a condition block in the 'if' statement

guard let var1 = par1
print(var1) // var1 is non optional here already

Supports all kind of statements that bring out of the scope: return, throw, continue, break

Example:

struct TextFiled {
  let text: String?
}
var name = TextFiled(text: "Dmitry")
var age = TextFiled(text: "35")
var city = TextFiled(text: "Lund")
var occupation = TextFiled(text: "iOS Dev")

// 'if' statement version
func validateFormIf() {
   if let name = name.text {
      if let age = age.text {
         if let city = city.text {
             if let occupation = occupation.text {
                print("\(name)\(age)\(city)\(occupation)")
             } else {
                print("occupation is empty")
             }
         } else {
            print("city is empty")
         }
      } else {
         print("age is empty")
      }
   } else {
       print("name is empty")
   }
}

// 'if' statement refined version
func validateFormIfRefined() {
   if let name = name.text, name == "" {
      print("name is empty")
   }
   if let age = age.text, age == "" {
      print("age is empty")
   }
   if let city = city.text, city == "" {
      print("city is empty")
   }
   if let occupation = occupation.text, occupation == "" {
      print("occupation is empty")
   }
   print("\(name.text!)\(age.text!)\(city.text!)\(occupation.text!)") // ALARM: Force unwrapping
}

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