Swift’s “guard”
Guard statement is an awesome new addition to Swift. You can think of it, as if used in the right way it actually does what a guard does in real.
A school guard like would only allow the students to enter belonging to that school. A student of another, if tries to enter is stopped right there and asked to go back. That is exactly what a guard statement will do if the condition following it is not met.
Less talk some code now !
guard in Functions
func printString(string: String?) {
guard string != nil else { return }
print(string!, separator: "", terminator: "\n")
}
The function is guarded against any nil inputs. If the input is nil, guard will execute the else clause and return from the function before any other statement is able to run.
Optional Binding
Heard of optional binding , Yes guard statement support it. Using it, the previous code block can be rewritten as
func printString(string: String?) {
guard let stringToPrint = string else { return }
print(stringToPrint, separator "", terminator: "\n")
}
Now if the argument ‘string’ is nil than it will execute the else clause if not than the function will continue to run normal and will print the string. If you have been using optional binding using if-let syntax you might notice something different here. We are using the optionally bind constant outside the scope of the conditional. In the case of if-let, we could only use it inside the brackets succeeding ‘if’ only when the condition is true.
In the case of guard statement if the condition is true than the constant’s scope is rest of the function. We can use it anywhere after it.
Compound Optional Binding
We can also use compound optional bindings like in the following example.
func printBio(firstName: String?,lastName: String?, dateOfBirth: String?, country: String?) {
guard let fName = firstName,
let lName = lastName,
let dob = dateOfBirth, let cnt = country
else {
print(“Bio is not complete”, separator: “”, terminator: “\n”)
return
}
print(“\(fName) \(lName) \(dob) \(cnt)”, separator: "", terminator: "\n")
}
Transferring Control
Another thing to note in the above example is if the condition is not met we return from the function. This is because guard statement must have transfer control in order to leave the scope in which it resides, if the condition following it is not met. In the example above we have used “return”. In the case of a loop we could use “continue” or “break”. We can also throw an error. Let’s look at an example.
var strings: Array<String> = [“Safe”, “Coding”, “why”, “using”, “guard”, “statement”]for string in strings {// We don’t want the ‘why’ string to be printed because it violates the grammar of the sentence. guard string != “why” else { continue }
print(string, separator: "", terminator: "\n")
}
// Safe Coding using guard statement
Here if the condition is not met we use “continue” in the else clause to transfer control.
That is it for guard.