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
It really really does make the flow of a sequence with several lookups and optionals much more concise and clear and reduces lots of if nesting. See Erica Sadun post on replacing Ifs. .... Could get carried away, an example below:
let filteredLinks = locationsLinkedToList.filter({$0.actionVerb == movementCommand})
guard let foundLink = filteredLinks.first else {return ("<Person> cannot go in that direction.", nil, nil)}
guard filteredLinks.count == 1 else {return ("<Person> cannot decide which route to take.", nil, nil)}
guard let nextLocation = foundLink.toLocation else {return ("<Person> cannot go in that direction.", nil, nil)}
See if that sticks.
Guard statement going to do . it is couple of different
1) it is allow me to reduce nested if statement
2) it is increase my scope which my variable accessible
if Statement
func doTatal(num1 : Int?, num2: Int?) {
// nested if statement
if let fistNum = num1 where num1 > 0 {
if let lastNum = num2 where num2 < 50 {
let total = fistNum + lastNum
}
}
// don't allow me to access out of the scope
//total = fistNum + lastNum
}
Guard statement
func doTatal(num1 : Int?, num2: Int?) {
//reduce nested if statement and check positive way not negative way
guard let fistNum = num1 where num1 > 0 else{
return
}
guard let lastNum = num2 where num2 < 50 else {
return
}
// increase my scope which my variable accessible
let total = fistNum + lastNum
}
With using guard our intension is clear. we do not want to execute rest of the code if that particular condition is not satisfied. here we are able to extending chain too, please have a look at below code:
guard let value1 = number1, let value2 = number2 else { return }
// do stuff here
Simply put, it provides a way to validate fields prior to execution. This is a good programming style as it enhances readability. In other languages, it may look like this:
func doSomething() {
if something == nil {
// return, break, throw error, etc.
}
...
}
But because Swift provides you with optionals, we can't check if it's nil and assign its value to a variable. In contrast, if let
checks that it's not nil and assigns a variable to hold the actual value. This is where guard
comes into play. It gives you a more concise way of exiting early using optionals.
One benefit is elimination a lot of nested if let
statements. See the WWDC "What's New in Swift" video around 15:30, the section titled "Pyramid of Doom".
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”.