Optionals are basically a way to say “This may or may not have a value”.
A lot of newbies are unsure of what optionals are and how they work so I’ll hopefully try to explain this in an easy way to understand.
Your are building an app that requires users to sign up.
The sign up form has fields for first name, middle name, and last name.
As you see I’ve created simple constants like so:
Each constant 100%, no doubt has a value in this case.
Print out as a full name like so:
Some people don’t have a middle name, so that’s where optionals come in.
We can tell Swift middleName may or may not have a value by adding a ? next to String.
Now notice when you print() fullName, you get some weird outcome like:
Steven Optional("Paul") Jobs
This is because we need to unwrap this optional.
This is pretty discouraged as it causes runtime crashes. Mainly because most beginner programmers just go with what Xcode suggests, which is to add a !.
! tells Swift, I know 100% certain this has a value, so you better be damn sure it contains a value otherwise expect a crash.
Since we do have a middleName, Paul let’s use ! in our print() statement.
Now we will get this in our console.
Steven Paul Jobs
Though we do have the wanted outcome without the Optional(“Paul”).
It’s just not safe to do it this way.
Change middleName like so:
We simply made middleName equal to nil.
Now we get a fatal error:
unexpectedly found nil while unwrapping an Optional value
This is because we explicitly told Swift by putting ! your 100% certain that middleName has a value which in this case it doesn’t therefore it crashes.
Safely Unwrapping Optionals.
You can use if let statement to safely unwrap your optionals.
Simply like so:
Basically this translates to:
If there is a middleName, take the value and store it in middle else do something.
Notice: we don’t use middleName, instead we use middle since that’s where the unwrapped value is stored.
In a previous post I covered guards, and how they can be beneficial.
Here I’ll show you how to use guards to unwrap instead of using an if let statement.
Now you safely unwrapped the optional without the chance of crashing.
I hope you now understand how optionals work and how to safely unwrap them.
If you have any questions or suggestions on what you’d like to read about next don’t hesitate to let me know 😊.