From the course: Swift 6 Essential Training

Introducing optionals

- [Instructor] If you're coming from a C-style language, the concept of objects having nil values shouldn't be news, but in Swift, any variable type can hold a nil value as long as it's declared as an optional. Optionals tell the compiler that the variable is either storing a value or storing nothing, which is useful when you need placeholders for potentially unknown values without crashing your code. I'm going to declare two optional variables here. They're declared just like any other. So we'll say var, and I call this itemGathered, give it a string type, and to mark it as an optional, we're going to add a question mark. I'll do the same thing and name a new variable, isExchangeable, and this is going to be an optional boolean. You can see in the inspector that both of these, because they lack initial values, are stored as nil, which is fine. That's not to say that we can't have initial values. So let's add pickaxe to itemGathered. Now, if we try and print out itemGathered, we're going to see something interesting. It's not actually going to print out the value or the string pickaxe. It's going to print out the optionally wrapped pickaxe. Now this is Swift's way of telling us that we need to gracefully and safely unwrap the string value before getting to it. We'll also get a warning if you click on the yellow triangle at the top of the editor, that our expression is implicitly coerced from string optional to any, which is a very confusing way of saying that itemGathered has not been unwrapped or addressed as an optional. What we can do for optional values is unwrap them in two ways, using optional binding or force unwrapping. We're going to get to optional binding later on when we talk about control flow, so for now let's force unwrap itemGathered by adding an exclamation mark. Now the actual string pickaxe is printed out, and it's no longer an option. Now be careful with force unwrapping because essentially what you're doing is telling the compiler that you're 100% sure the optional is not nil, and to immediately unwrap it without checking. If we tried to print out and force unwrap isExchangeable, we're going to get a crash because it's nil, and we basically overrode the compiler and took away that safety measure that it's implementing for us. So let's comment that out, just so we can keep going with our program. Now from my point of view, forced unwrapping sort of defeats the purpose of having optionals in the first place. They exist specifically to save you from having to remember if a certain variable is nil or not. So don't form a habit of force unwrapping. To sum up, optionals either store a value or nothing at all. They're compatible with variables or constants, and can be declared with any type.

Contents