Welcome to yet another Swift Deep Dive. In this episode, 1
we're going to talk about Optionals (!?). And what the heck are "Optionals"? 2
So we keep seeing these exclamation marks in question marks all over our code, especially when we find 3
it from StackOverflow or when we see it in the Swift Documentation. 4
Now what exactly does it mean and how do we use it? 5
So in order to understand this better, I want to introduce you to our shed cat Fluffy. 6
So this is our cat that we have to look after now, you and me. But we have to transport our cats and 7
we're going to do that in a cardboard box. 8
So Fluffy goes into the box and we're pretty sure that currently, we have definitely a real cat in the 9
box. 10
Meow. 11
But let's say that during the hectic time of moving, we also accidentally popped a bottle of poison into 12
the same box as Fluffy. 13
So now we package it up and we kind of moved around in the van, shake it around, and the poison bottle 14
might be broken. And we now basically have an optional cats, 15
right? 16
We have a cat with a question mark at the end of it. 17
We don't know if Fluffy is dead or alive. And if we were to force open or force unwrap our box and see 18
what's inside, well, we might discover that, indeed, we do still have Fluffy. She's alive and well and she's 19
smart enough to not eat the poison because, you know, we're good at rearing cats. But we might also find 20
that Fluffy is no more, 21
she got tempted by the poison. It smelt like Play-Doh, 22
so she had a little bit. And now Fluffy is dead. 23
So we might actually have no cat, which in programming lingo, we would call nil. 24
This is essentially how optionals work. 25
There's frequently cases where you need a container, 26
so a variable, that might often need to start out containing no data. 27
Let's say that you had a field in your app where you were going to save the user's username. Well, before 28
they actually created that username variable is going to be nil. But then, hopefully, at a later date, 29
when you need to use the username to display it on screen or to use it in some way, then you're hoping 30
that the user has ready filled it in. 31
So it does, in fact, have a value. In order to represent this uncertainty in Swift, we use something called 32
optionals. 33
So you've seen that when we create a variable, we can specify a data type at the point of creation. 34
So we could add a colon and then add the type of data that this variable or this container or cardboard 35
box is going to store. 36
But then we can add a question mark at the end of our data type to turn it into a completely different 37
data type and it becomes a optional data type. 38
So now this variable hardness can store a string or it can simply be empty. 39
It could have no data or store nil. In a blank playground, 40
I'm going to create a new variable and I'll call it player1Username and I'm gonna set it to be a 41
string data type. 42
And at the very beginning of the game before any player has even gotten the chance to assign themselves 43
a username, 44
well, this variable is not going to contain any data, 45
right? It's going to contain no data or nil. 46
And as soon as you try to run this, because our variable is mostly meant to hold data of string data 47
types, it gives us an error. 48
So we can't just simply take a normal variable container and try to give it no data. 49
What can we do instead? 50
Well, we could instead create a variable called player1Username. and instead of assigning it to a string 51
data type, we give it a string with a question mark at the end. 52
So now it's a optional. 53
And now I can quite easily say that actually this player1Username, it has no data stored 54
in it. But at a later date, I'm going to ask the player, "Well, what is your username?" 55
And they'll give me a username which might-- Let's say, "jackbauerisawesome," so now I have a value inside 56
my optional player1Username. 57
So if I was to print my player1Username at this point, you will see a optional string being printed, 58
So the word "Optional," and then a string. 59
So how can we turn it from an optional, which it is at the moment, which you can see right here, but you 60
can also check by holding down the optional Alt key, 61
you can see that it's data type is clearly an optional string. 62
Well, we could simply just force unwrap it. So we unwrap our box and accept whatever the consequences 63
may be and we try to use the unwrapped version. 64
Now, if I run my code, again, you can see that my optional has become a normal string again. 65
And in fact, if I simply go ahead and create a new variable called unwrappedP1Username and I set 66
it equal to player1Username unwrapped, then you can see that when I check the data type of this 67
unwrappedP1Username, it's now back to a normal string. 68
So it's no longer an optional anymore because I have overridden the safety check. So the safety check 69
is there to prevent us from crashing and burning when we try to do something with a nil value, so a null 70
value. Let's say, if at some later point, I changed my player1Username to, again, equal nil. 71
So let's say that the player has reset their username and, in fact, I'm going to common out this line 72
just to make it a bit clear what's going on here. 73
So we started out by creating a container that can hold nil values, 74
so an optional string data type. And it started out being nil, but then we gave it a value, but then we 75
remove the value and player1Username no longer contains any data on line 10. 76
So now if we try to print it and we unwrap it forcibly, saying that "I am so sure that this will definitely 77
always have data. Computer, 78
listen to your master, which is me the programmer. Just do as I say." And we run it and then all it's going 79
to do is crash. Because if we have a nil value that we're trying to do something with, say, we're trying 80
to add two to nothing. It doesn't make any sense 81
if we try to print nothing, if we try to do anything with a nothing data. It's like taking thin air 82
and trying to do something with it, 83
so that's when our app would crash. In order to prevent this from happening, 84
we can enact some safety checks. 85
The first safety check is, actually, your brain. 86
The reason why a lot of things are optionals are that you are reminded that some of these values can 87
have nil as its value. 88
You want to be able to check through the code and make sure that it won't ever become nil. 89
Now another way of doing this is we can actually just explicitly check to see if player1User name 90
does not equal nil. 91
So that's what that exclamation mark equals mean, 92
means does not equal. 93
And in that case, 94
well, then we could use it and we can unwrap it forcibly. Because now, even though player1Username is 95
equal to nil, our app is no longer going to crash because it's going to bypass the line that would cause 96
an issue because this is not true. 97
Player1 is, in fact, equal to nil. Then we're going to skip the line and we're not going to crash our 98
app by using a piece of data that's nil. 99
Now, there's a really fun comic that somebody once made on "If programming languages were weapons," and 100
one of the biggest problems with a lot of older languages like Java is this idea of a NullPointerException. 101
So this is essentially the same as what we've been talking about. 102
So it says that Java is a belt-fed 240G automatic weapon where sometimes the belt has rounds, sometimes 103
it doesn't. 104
So sometimes it has data, sometimes it's equal to nil. And when it doesn't and you try to fire it, then 105
you get an NullPointerException or you get an error like we did, 106
and the gun explodes and you die. 107
So this is one of the biggest problems with some of these older languages. And the way that Swift was 108
designed is to be a safer language. So the gun doesn't explode in your face and you actually have 109
a fun time using it. 110
But in order for it to work, we have to understand when we're using an optional and to make sure that 111
if we are unwrapping it with an exclamation mark, that we're certain, that it's never going to be equal 112
to nil. If we're not certain, then we should probably check for it and to prevent our app from crashing, 113
so that lines, where we're unwrapping, are optional, are protected by an "if" statement. 114
Now, in later lessons, we're going to dive deeper into some other fancy things that you can do with optionals, 115
such as optional chaining and optional binding. 116
But for now, I just wanted to introduce you to the idea of a nil value that a variable can actually contain 117
no data at all. 118
And the idea that if you tried to do something with nil, then your program will likely crash and optionals 119
are there to safeguard us from these situations, first, by making us think about whether if it could be 120
nil 121
and, second, by getting us to protect against those scenarios. 122
So now that you've learned a bit more about optionals, it's time to complete the assignment that is on 123
Beginning Optionals. And on the next lesson, we're going to head back into building our app. 124
our app.