Using Guard
suggest changeguard checks a condition. If the condition is false, it enters the else branch. That branch must leave the enclosing scope with return, break, continue, or throw. Failing to do so is a compiler error. Once a guard is written, flow cannot continue accidentally the way it can with an if.
Using guards can help keep nesting levels low, which usually improves the readability of the code.
func printNum(num: Int) {
guard num == 10 else {
print("num is not 10")
return
}
print("num is 10")
}
Guard can also check if there is a value in an optional, and then unwrap it in the outer scope:
func printOptionalNum(num: Int?) {
guard let unwrappedNum = num else {
print("num does not exist")
return
}
print(unwrappedNum)
}
guard can combine optional unwrapping and a condition. Swift 2 used where. The comma form below is Swift 3 and later:
func printOptionalNum(num: Int?) {
guard let unwrappedNum = num, unwrappedNum == 10 else {
print("num does not exist or is not 10")
return
}
print(unwrappedNum)
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents