Often when working with Swift Optionals, we will want to perform an action if the Optional contains a value, or do something else if it does not. This is done with Optional Binding with the “if let” syntax, which lets us test for wether it contains a value, and if it does, binds it to a constant that can be used later in the if statement. This works great for many cases, but it does put the emphasis on the positive case. If there is a value, do this, otherwise do that. Now if the code to run when there is a value is short, you can easily see what the “else” clause is tied to. However, if the code to run when there is a value is long, then you might need to do some scrolling to see the associated else clause.
This is where the guard statement comes in handy, introduced with Swift 2. The guard statement puts the emphasis on the error condition. In this case, if there is no value, you can clearly see what will be done to deal with it.
What happens if there is a value? The rest of the current scope continues running like normal. Let’s go into an example of how the guard statement can be helpful.
[Read more…]