Swift 2: guard

In Swift 2, there is a new keyword for handling the control-flow of a block of code. It guarantees, that a specific condition holds true for the further code. Otherwise, it ensures that the following code will not be executed.

Let us start with a simple example. Imagine you have a function, that has an optional as an argument:

Because a  is an optional, you need to check whether a  is nil or not.

In this situation, guard gives you a simpler possibility:

In the guard condition, there is conditional binding of a . If it fails, the else part of the guard statement must ensure that the following code will not be executed. In this case, the function is returned.

After the guard statement,  a is not an optional anymore, which makes the handling of optionals easier then before.

Generally, the guard statement can be used everywhere, where one of the following statements can be called:

If none of these keywords are called, there will be a compiler error!

So you can for example ensure, that a condition holds for a loop iteration:

Another good application case is throwing an error. Our previous example can be rewritten to

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon