Checking up front with guard
We have seen in previous recipes how we can use if
statements to check Boolean expressions and unwrap optional values. It's a common use case to want to do some checks and conditional unwrapping at the beginning of a block of code, and then, only execute the subsequent code if everything is as expected. Often, this results in wrapping the whole block of code in an if
statement:
if <#boolean check and unwrapping#> { <#a block of code#> <#that could be quite long#> }
Swift has a better solution expressly for this purpose--the guard
statement.
How to do it...
Let's imagine that we have some data that came from an external source, and we want to turn it into model objects that our code can understand and perhaps display it to the user:
- First, for the purpose of this example, let's create the data that can be from an external source; in this example, it is data on the planets of the solar system in the form of an array of dictionaries:
//...