KnowledgeCity

Swift Intermediate: Optionals in Swift

In Swift, variables and constants are not automatically initialized.

In Swift, variables and constants are not automatically initialized. Default values are very common in other languages, but default values can lead hiccups in your code you might not expect. Because Swift focuses on code safety, it solves the problem of inherently chaotic default values with optional values or optionals. 

Optional values might or might not have a value, but it’s very important, when using an optional value, that Swift understands whether there is or is not a value. A value of nothing is nil, and Swift can’t calculate nil, so we have to tell Swift to use the value or ignore it.

In this module, you’ll learn how to use optionals. You’ll explore how to create them and use them in your code safely. You’ll learn how to use the nil coalescing operator and optional binding or the if-let statement so your code is safe from unwanted crashes. You’ll also learn about guard let. You’ll use this when you want to gracefully exit a function if you come across a nil value.

Learning Objectives

  • Recognize optionals
  • Understand the nil coalescing operator
  • Explain if let and guard let

Author: Mark Nair

Duration: 27m · 4 lessons
Level: Intermediate
Language: English

Skills you’ll gain

Function ModuleFunctional ProgrammingSwift (Programming Language)

What You'll Learn

  • Recognize optionals and understand how Swift handles values that might or might not exist
  • Create optionals and use them safely in your code
  • Apply the nil coalescing operator to provide values when an optional is nil
  • Use optional binding with the if-let statement to safely unwrap optionals
  • Use guard let to gracefully exit a function when encountering a nil value

Key Takeaways

  • In Swift, variables and constants are not automatically initialized, so default values are not assumed as they are in many other languages.
  • Swift focuses on code safety and uses optional values to solve the problem of chaotic default values, since an optional might or might not have a value.
  • A value of nothing is nil, and because Swift can't calculate nil, you must tell Swift to either use the value or ignore it.
  • The nil coalescing operator and optional binding (if-let) keep code safe from unwanted crashes when working with optionals.
  • Guard let is used to gracefully exit a function when a nil value is encountered.

Frequently Asked Questions

What does this Swift module cover?

This intermediate module teaches how to use optionals in Swift, including how to create them and use them safely, the nil coalescing operator, optional binding with the if-let statement, and guard let for gracefully exiting a function when a nil value is encountered.

Why does Swift use optionals?

Because Swift does not automatically initialize variables and constants and focuses on code safety, it uses optional values to solve the problem of chaotic default values. An optional might or might not have a value, and Swift needs to understand whether a value is present.

What is nil in Swift and why does it matter?

A value of nothing is nil. Swift can't calculate nil, so when using an optional value you have to tell Swift to either use the value or ignore it, which is why optionals and safe-unwrapping techniques are important.

What lessons are included in this module?

The module includes four lessons: What are Optionals?, The Nil Coalescing Operator, Using If Let, and Using Guard Let.

What skills does this module relate to?

This module relates to Swift (Programming Language), Functional Programming, and the Function Module.

Transcript

Show transcript (free preview lesson)

Transcript of the free preview lesson. Remaining lessons unlock with the full course.

Hello, my name is Mark Nair and in these lessons you'll learn about optional values, the nil coalescing operator using if let and using guard let. In Swift we can define our constants and our variables but we don't have to give them a value at the beginning. We just have to give them the value when we use it. But if we don't do that, we have to give them a type. Let's take a look. If I just say let name, Swift will say, "I don't know what you're talking about, type annotation missing in pattern is the error." So I have to do something about that. I have to give it a type. Same thing here. If I have a number, same issue, and then we can get away with it. But we really can't use it yet. If we try to use it, we get a problem. We have not initialized the value. Unlike other languages, variables and constants in Swift don't get any initialization at the beginning automatically. That's common some other places, but not in Swift. Swift is about how we use things very safely. And if you have a default automatically built in, you might run into problems later. For example, if name were default value of just an empty string, and later on if we're accessing the value of name and we have forgotten or we haven't given any value ourselves, we'll just get this and we're printing nothing. Well, we're actually just printing an empty string. There is some value there. So Swift takes the other way around, says, "You better know what you're doing. You better give me a value for sure." There are times though that having no value makes sense. So for example, let's say that you are a singer. You're a famous world singer, your name is Sting. Sting doesn't have a last name, not including his real name yet. But let's say Sting is using one of your apps, says, "What's your first name? What's your last name?" Sting says, "I don't have a last name." Then what do you do? So we could have, but then what happens? Okay, I'm Sting, I'm firstName. There is something in Swift for no value. If you used a default of an empty string, Sting's name would be Sting empty string. That's not really the name, it's just Sting. So we have in Swift a thing called an optional. And an optional value is exactly what it says. It is an optional thing that you either have a value in it or you have no value. And no value means nil, which is a special word in Swift. Now, the way we distinguish that is after the type we use a question mark. And think about it like this. There's a value, I don't know, it's a question. So last name doesn't have a value. Now, just because it's an optional it means it still needs to have a type. In this case, last name is type optional string. It doesn't mean it is just an optional, it's still a type. And when there's nothing in there, the value is nil. So optionals may or may not have a value. We use this question mark to add it to distinguish that. So let's do this function. So getLycanthropeStatus returns a string and it's just very simple function. And if I run it, all we'll get is the return value of werewolf. Okay, that's the status, you are a werewolf. Now let's change the function. So what if somebody isn't a werewolf and they're nothing. It's not a werewolf and not a not-werewolf, it's just a nothing. So I'm gonna make this the value of an optional string. So now let's change the function to give us some kind of conditional. Now I will call the function. When the moon is, when it's a new moon then the value is nil. But when the moon is full, the value is werewolf. So in new moon, I have this optional value of nil. So let's see what happens when we have nil. Set up a new variable called wolfStatus. Then I will make this wolfStatus, and I run into a problem. Value of optional type string must be unwrapped. So when we have optionals, think about them as a little box. There might be a value in the box. There might be no value in the box, nil. But in order to use that value safely, we have to unwrap that box in a nice, safe way. If I take a peek at wolfStatus here, the string. So right now it's a string because I've denoted it here. But if I comment this out and run this and if I Option + click wolfStatus, the value now, the type is an optional string. If I try to use that, I'll see nil. Nil. When I say we need to unpack the optional, what I mean by that is just look at the optional as a is something in a box and it's either has no value or a value, and we need to unpack that safely. There's a way of unpacking it where we're ripping the box apart, and that's what I'll show you now and then I'll show you how to do it safely and it makes your code much smoother. So let's do another example here of circusJob. Now, one other thing, in the documentation the way to actually give an optional value is this. Looks like the long way about it, but it's very explicit. It is optional with the question mark here. Now, we don't have to do this, we can just do this. But just so you know, if you ever look at it. So right now I have a circusJob optional string of Magician. I'm gonna concatenate this string this time because it will really show you what happens. Now if I run, well, I can't even run it. The value, we get this red thing, value must be unwrapped. Now, if I click this error, I can coalesce using two question marks or force unwrap using exclamation mark to abort execution if the optional value contains nil. Well, let's do that one. So I'll just choose this. Now, running it, it's perfectly fine. That's because this explanation mark is the way of ripping open that box, like of the Hulk. You're just tearing off the sides and getting to the value but you're not very delicate about it. Which means that if this value is nil, this force unwrapping will crash, and it's a nasty crash. So this is why probably the most of the time you don't wanna do a thing like this. This is exactly why I wanna show it to you show you what not to do so that you can see it. A safer method of getting around all this is I can use it conditional. So if a circusJob is not equal to the value of nil, now we'll still get an error here because we still have to unwrap this. But in this case, we are double checking. So we can force unwrap the value, but we won't crash if it's nil. And let me show you what that means. So right now, if it's not nil, I am a magician, right here. If it is nil, then the conditional will take care of that for us. And then the description, I don't work at the circus. This is just force unwrapping. There are other methods of doing this much nicer, much cleaner and safer. Thanks for watching. Stay tuned for the next lesson where I'll show you how to use the nil coalescing operator.

Learn on the Go

Take your learning anywhere — the KnowledgeCity mobile app lets you watch lessons on the go.