Swift 2 introduced the guard
keyword, which could be used to ensure that various data is configured ready to go. An example I saw on this website demonstrates a
Source: Guard in Swift
Let's see the example to understand it clearly
Example 1:
func validate() {
guard 3>2 else {
print ("False")
return
}
print ("True") //True
}
validate()
In the above example we see that 3 is greater than 2 and the statement inside the guard else clause are skipped and True is printed.
Example 2:
func validate() {
guard 1>2 else {
print ("False") //False
return
}
print ("True")
}
validate()
In the above example we see that 1 is smaller than 2 and the statement inside the guard else clause are executed and False is printed followed by return.
Example 3: gaurd let, unwrapping optionals through guard let
func getName(args myName: String?) {
guard let name = myName, !name.isEmpty else {
print ("Condition is false") // Condition is false return
}
print("Condition is met\(name)")
}
getName(args: "")
In the above example we are using guard let to unwrap the optionals. In the function getName we’ve defined a variable of type string myName which is optional. We then use guard let to check whether the variable myName is nil or not, if not assign to name and check again, name is not empty. If both the conditions qualified i.e. true the else block will be skipped and print “Conditions is met with name”.
Basically we are checking two things here separated by comma, first unwrapping and optional and checking whether that satisfies condition or not.
Here we are passing nothing to the function i.e. empty string and hence Condition is false is print.
func getName(args myName: String?) {
guard let name = myName, !name.isEmpty else {
print ("Condition is false")
return
}
print("Condition is met \(name)") // Condition is met Hello
} getName(args: "Hello")
Here we are passing “Hello” to the function and you can see the output is printed “Condition is met Hello”.