Exiting Early from a Function
You learned about Swift’s conditional statements in Chapter 3, but there is one more to introduce: guard statements.
Just like if/else statements, guard statements execute code depending on a Boolean value resulting from some expression.
But guard statements are different from what you have seen before.
A guard statement is used to exit early from a function if some condition is not met.
As their name suggests, you can think of guard statements as a way to protect your code from running under improper conditions.
Following the example above, consider an example in which you want to write a function that greets a person by their middle name if they have one. If they do not have a middle name, you would ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access