O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required