O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

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

The guard statement

In Swift, and most modern languages, our conditional statements tend to focus on testing if a condition is true. As an example, the following code tests to see whether the variable x is greater than 10 and; if so, we will perform some function. If the condition is false, we handle the following error condition:

var x = 9  
if x > 10 { 
  // Functional code here 
} else { 
  // Do error condition 
} 

This type of code embeds our functional code within our checks and tucks the error conditions away at the end of our functions, but what if that is not what we really want? Sometimes, it might be nice to take care of our error conditions at the beginning of the function. In our simple example, we could easily check if x is less than ...

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