- It has a positive test rather than negative one
- 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
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()