- Mastering macOS Programming
- Stuart Grimshaw
- 227字
- 2021-07-02 22:54:31
The guard statement
The guard keyword is a little like a specialized edition of if else. It tests a Bool value, and if that value is true, then the guard statement has finished its work, and code execution continues with the next statement. If, however, the Bool value is false, then its else clause is executed. This clause must end in a return statement, which will leave the function in which the guard statement is used.
Here is an example:
func processEvenNumber(i: Int)
{
guard i%2 == 0 else {
return
}
print("\(i) is an even number)")
}
Now, on seeing that for the first time, you may think, as many do, "yeah big deal, I could have done that with an if statement." And that would be absolutely true, but the story's not over yet.
A guard statement offers three advantages to using an if statement:
- The code that comes after the (successful) test does not need to be wrapped in curly braces
- The guard statement enforces a return block (which may also contain any warnings and clean-up code that you may wish to include); failing to add one will result in a compiler error
- It encourages an early exit if the test fails
We'll look at some of the most common use cases for guard when we get to the optionals, later in this chapter.