Join Harrison Ferrone for an in-depth discussion in this video Break down optionals, part of Learning Swift 3 for Developers.
- [Narrator] I'm going to close out chapter four and start a new playground for chapter five. File, new, playground. Going to name this chapter five underscore optionals. Make sure Swift three for developers is our folder and hit create. Let's do our standard delete the comment and the default string, and add our own. Chapter five only in swift.
Optionals. Under the import I'm going to add a title. Breaking down optionals. So, optionals in Swift can be hard to wrap your head around at first. Especially since they don't exist in C sharp or C++ or even objective C. But let's go to the basics first and see if we can establish a strong understanding of the concept. An optional variable declaration means that there is either a value present or missing in the variable.
To put it another way, if you have an optional string you are saying that there may or may not be a string value associated with that variable. If there is a value present, you can unwrap and access it but in the case where the value does not exist, the compiler with throw an error. Now we'll cover unwrapping optionals a bit later on but just know that this is Swift's way of letting us deal with null values efficiently and with significantly less hair pulling. Let's declare our first optional.
We're going to call it our first optional, and it's going to be of type string. Now to declare an optional in Swift you add a question mark. We can also give our first optional an initial value. Going to say optional string. Let's declare another optional called second optional. It's also going to be of type string, and don't forget the question mark. Both of these are valid ways to declare an optional. We can also declare empty optional variables just like we've done before.
Var empty optional and this time I'm going to make it an array of strings. Equals open and close brackets. Now let's go over what we've done. Our first optional is an optional string that has a default value. Our second optional is also a string optional but since we didn't give it a default value, it's going to have nil. Our empty optional is exactly what it sounds like.
It's an empty optional of type string array. We can always change these values later on. For instance, our first optional could be set to nil, and our second optional could be set to coming to an optional near you. With optionals, whether their values are nil or an actual value, we are protecting ourselves from null exceptions.
- Starting a new playground
- Printing to the console
- Declaring variables
- Working with numbers
- Using strings
- Breaking down optionals
- Understanding closures
- Classes vs. structs
- Extensions and protocols