Programming in Swift: Fundamentals

Oct 19 2021 · Swift 5.5, iOS 15, Xcode 13

Part 1: Core Concepts

07. Optionals

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 06. Challenge: Logical Operators Next episode: 08. Challenge: Optionals

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 07. Optionals

Update Notes: The student materials have been reviewed and are updated as of October 2021.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

So optionals can be real point of confusion for beginners in Swift. When you start to see a bunch of exclamation marks and question marks puncturing Swift code, you probably would kind of wonder what's happening. Well, to start with, when you see those two things at the end of a bit of code, that indicates you're looking at what's known as an "optional". To explain what optionals are and why they're helpful, let's think about a common problem a programmer might come across. So let's say you're making an app to keep track of your friends. You want to store their first name, their last name, and if they have one, the name of their pet. If I add myself to the app, it's easy. I'd put Chris for the first name, Belanger for my last name and Mango for my dog's name. But what if I was putting someone else into the app, like Ray? We know his first name is Ray and his last name is Wenderlich but does he even have a pet? Hey folks, does Ray even have a pet? [camera crew member] No, he's allergic. Oh, no pet. What are we going to do? We need a way to model the concept that Ray doesn't have a pet. You might think to do something like use booleans to track if someone has a pet or not has a pet or use an empty string for the pet's name. And there's lots of ways you could model this yourself, but you don't have to. Swift already has a great solution for this: optionals, Optionals in Swift let us represent either a value or the absence of a value, which is called "nil". I think of optionals as a kid-friendly version of Schrodinger's cat. If you're not familiar with that concept, there's a box that might have a cat inside, or it might not have a cat inside. The trick is you don't know if this cat inside until you open the box. Hey, there's a cat. This optional had a value of Princess Ozma. Thanks for helping us out Ozma! Now let's check another one. Hmm. It looks like this one's nil. Now we could use optionals like this to solve our earlier dilemma. We could have an optional box for the cat's name and there might be a cat's name inside, or it might be nil. And one more important thing to note, optionals all have a type. Have an optional cat, you won't open the optional and find a Cocker demon inside. It's either going to be a cat or no cat. An int or no int. A string or no string. Now that you've got an idea of what optionals are about, let's see what they look like in code. To create your first optional, let's use that pet name example. So create a variable called "pet name" and make the type a string. To turn this into an optional string, all you have to do is add a question mark to the end of the type. And you can see the sidebar that if you don't give an optional a value right away, the default value is set to nil. Now to make things example less sad, let's change the value to Mango. In the sidebar, you see the value of set to Mango as you'd expect, but if you try to print out the value, you'll see optional Mango in the console. That's because the value is still wrapped up inside the optional. Now you'll get into how to unwrap optionals in just a moment but first, how do you change an optional back to having no value? Oh, to set an optional back to nil, you just use the keyword "nil", instead of a value. Now, back to unwrapping optionals. Now, opening the box you saw earlier is a lot like unwrapping optionals. You want to get to the actual real value inside the variable and see if you can work with it. I'm going to make a quick optional int to illustrate something before we really get started here. So you know that optionals are typed. And this one is an optional int. Throughout this course, I've encouraged you to use type inference to shorten up your code where you can, but you can't use type inference when you create optionals. If you get rid of the type and you've given the variable a value, the compiler assumes it's a regular int, not an optional int. And if you change the value to nil, then the compiler has no idea what you want and you'll get error, just like this one. So when you declare an optional, you need to explicitly type it every single time. So with your optional properly declared, you're ready to go back to the problem you saw, when you tried to print an optional string. We see the same thing with this optional int. And even worse, if you try to add an optional int to an int, and the problem is spelled out for you in red and white right here. To use the values inside of optionals, you have to unwrap the optional. Let me get rid of this. So remember the compiler doesn't actually know if the optional has a value or if it's nil until you actually unwrapped the optional. Now, there're several ways to unwrap optionals. The easiest way is called "force unwrapping". To try that out, let's declare a new variable called "pet age" to go along with my pet name, Michelle said here. Now, I've used my dog's age here again, but you can use any cat or dog or snake or lizard or human being that you like. Now, let's create another variable to store the unwrapped pet name. And this little exclamation mark at the end is how you force unwrap an optional. It says, "I don't want to carefully check this option and see if there's something inside before I use the contents". "I want to open it now". But force unwrapping is the easiest way to unwrap an optional, but it's also the most dangerous. So in this case, pet name has a value. So if you try to print it out using string interpolation, you get the value expect in the console. But, in the various sad, sad case where there is no pet name, ooh, we got a big fatal error that would crash our app. Oh no! Therefore, you should only use force unwrapping when you absolutely know an optional has a value. Luckily there are other ways to safely unwrap optionals. The first one we'll share is called "optional binding". Now optional bonding looks very similar to an "if else" statement. Now, the first line is basically shorthand for this. Now, optional binding used to sound like fancy jargon to me, but all it means is that if this optional is not nil, which means it has a value, store the value in this new constant. You're binding the value to the constant. When you use optional binding, it's really common to name the constant as the same as the optional you're unwrapping. Now, this technique is called "shadowing". This new constant pet name only exists within this block of code. So it won't conflict with a variable called "pet name" that you declared earlier. You'll learn more about this idea of where variables exist later on in this course, when you learn about the concept of scope, but for now, just know that this constant only has effect inside this "if else" statement and nowhere else in your code. Now, what if you want it to use both "pet name" and "pet age" at the same time? Well, with optional binding, you can unwrap multiple things. One right after the other. You just needed a comma, separate the bindings. Now you can add a print statement using both of those unwrapped optionals. When you unwrap multiple optionals like this, it's a bit like using the "and" operator. All the optionals here have to have values in order to proceed. If any of the optionals are nil, this code is skipped and the "L" statement executes instead. In fact, you can even add bullying conditions to this statement, if you want it to. Now, there's one last way I'll show you how to deal with optionals. And that's called "nil coalescing". So let's say have an optional like this optional in here. Now, if you absolutely need a value that isn't nil, you can use the nil coalescing operator to unwrap the optional and if there's no value in there to provide a default value instead. To use this operator, you put the optional you want to check on the left. Then the two question marks and then the default value. So you can see that currently optional int has a value of 10. So required result is also 10, but if you change optional int to nil, required result is set to the default value of zero. All right, now I've got some optional challenges for you. I mean, the challenges are about optionals, the challenges themselves aren't optional, but there are optionals in the challenges. Okay, just go to the challenges and you'll see what I mean.