Hey Guys! This is the next part in the Beginner’s Guide to Swift series, and today we will be talking about optionals in further detail and optional binding. If you didn’t catch my last blog post, please read that one before reading this one, as this post expands on concepts covered in the previous post. The primary topics of this post will be optional binding and optional chaining. With that being said, let’s get started!
Last time, we talked about force unwrapping, where if we were confident that the optional was not nil, we added an exclamation mark next to the variable to indicate to Swift to treat it as a normal variable.
However, when you are programming, you will often find yourself using chains to access attributes of several objects, and those attributes may or may not be optionals. In those chains, if you have optional variables, and if at any time one of those optionals is nil, the whole statement will return nil. To get a better understanding of this concept, let’s take it to Swift!
We are first going to create two classes: a Student class and a Course class. Let’s create the Course class first, which will have a course name as an attribute.
Notice that the courseName is an optional, meaning that it could actually have a name, or it could be set as nil.
Now let’s create a Student class with two attributes: a String for studentName and an object of the Course class.
Remember, if you forget any of these concepts, please check out my older blog posts on classes, where I dwell on them in more depth. Let’s continue on with making the Student class.
You can see that the course attribute in the Student class is an optional, since a Student may or may not be taking a course. If he or she is not taking a course, that attribute will be set to nil upon instantiation.
Now let’s create an object of type Course called “courseOne.” This will not have a course name, so it will be set to nil. Next, create an object of type Student called “studentOne.” His name will be Bob and the course he has will be courseOne.
As you can see, studentOne is taking courseOne, which does not have a name at the moment.
Now let’s get to the optional chaining. Recall from earlier that optional chaining returns nil if a chain has any attribute returning nil. Let’s try this out. We will try to access studentOne’s course name and check to see whether the course name is empty or not.
Okay, let’s try to understand what this last line means. It essentially states that if studentOne is taking a course (which is an optional because a student doesn’t necessarily has to be taking a course), check to see what the courseName of that course is, and then check to see if the courseName is empty. Now, we see that the statement is returning nil. Optional chaining returns nil if any of the optionals in that chain return nil. So what is returning nil here? Well, we stated that courseOne does not have a name, since courseName is set to nil. Because of this, the whole statement is returning nil.
We can see that if we change the instantiation of courseOne’s name to something concrete, the last statement will not return nil.
Immediately, you can see that the last statement returns false after we changed courseOne’s name to “Swift Class.” This is because nothing in the chain is returning nil. The course is not nil, and the courseName is not nil. So, the isEmpty function can do its job! It returns false, because courseName is obviously not empty!
You may be asking, what is the point of optional chaining? Well, the point of optional chaining is to save you a lot of extraneous code. If optional chaining did not exist, then we would be stuck with making several if-statements to check if the variables were equal to nil or not.
Sometimes we can use if-statements to bind optional variables to non-optional variables. What this binding does is that if the optional variable does NOT equal to nil, then it will assign itself to the variable you declared in that if-statement.
Let’s try this in XCode to get more sense out of this.
Delete everything except for the declaration of courseOne, and change it to nil as well. Now let’s create an if-statement which declares a new variable.
Okay so what are we doing here? We first created an if statement, and said if courseOne’s name is not nil, then assign that value to a new constant by the name of tempCourse. Then print out tempCourse.
However, courseOne’s name is set to nil! So, tempCourse is not being set to any value and is therefore returning nothing. If you change courseOne’s name to something other than nil, you will see its effects on tempCourse.
As you can see, after changing courseOne’s name to “Swift Course,” the if-statement is being carried out and assigning the courseName to tempCourse. That’s why tempCourse is being printed out.
It’s really important to understand this. In the if-statement, we are only using one “=” sign. This is a setter, or a function that sets the value of a variable. When we want to check if one variable equals another variable, we will use two equals sign.
It’s also really important to understand another thing. tempCourse is NOT an optional. It is just a normal variable and therefore cannot be set to nil. If we had declared tempCourse outside of an if-statement and set it equal to courseName, tempCourse would become an optional.
So this is an example of optional binding: if the optional has a value other than nil, bind it to a variable or constant and keep that a non-optional. Then carry out whatever is needed within the if block.
That’s it guys! This was way more advanced than our previous topics, so it is important to read over this a couple of times and try your own examples to really get the hang of it. See you guys next time!