So, Let’s dive in. If you’re not already familiar with the concept here’s a quick overview.
Optionals are variables in swift, that are optional. Now what this means is that you don’t need to set them, like you would with a normal variable. Generally when you create a variable like this, the compiler will tell you that the variable needs to be set to something. So in other words, it needs to be initialized, otherwise the compiler doesn’t know what to do with the variable.
Please note that this will only be a problem inside of a class or project inside of Xcode. Playgrounds do in fact allow this behavior and your application will crash later, If you try to use the variable.
Back to the instantiation. There are some cases, where you would not like to initialize your object. There can be multiple reasons for that, for example when you’re dealing with storyboard objects or if you’re not certain about what class an object belongs to. You can use optionals in those cases to make sure code only gets executed if certain conditions are met.
To create an optional, just append a „?“ at the end of the type declaration. Like this.
Scramble the eggs
In case this concept seems a little bit odd to you, let me just make it more tangible by using a simple example.
To give you a framework to work in, let’s say want to cook scrambled eggs. What would you need for that?
- a Pan
- some Oil
- some Onions
- and Eggs
This example is perfect for showing you how optionals work, but before we can continue, let’s just agree on a recipe.
- Heat up the pan
- Start dicing the Onions
- You get the eggs from the fridge
- You scramble
- and cook them
- And finally, you can serve them.
This whole recipe works really well and tastes really good if you have all your ingredients within your reach. But what if something goes wrong?
Let’s say we have the following situation: You just started heating up the pan, diced your onions and put a shot of oil into the pan. You walk over to the fridge to get the eggs, but halfway to there, you realize you forgot to go shopping. There are no eggs in the fridge. What this means, is that all your previous work is useless because you don’t have all the ingredients to continue with the recipe.
To me, this sounds really inefficient. I’d much rather check the fridge before starting the recipe, so I don’t waste any energy and time.
How does this tie in with our optionals? Quite simple! Just assume the eggs would be the optional’s and swift. You can’t be certain that there are any in the fridge, so you have to check. That is essentially what optionals do. Optionals are variables that can either be set to something or they contain nothing. When they contain nothing, we use a keyword called „nil“.
So, let’s just look at our scrambled eggs example in code:
Demo in Xcode
Next up we’re going to learn how to deal with optionals in a safe way.