Swift’s Optionals — A beginner’s guide (Part One)

The infamous optionals

When I was learning swift in the beginning, understanding the concept of optional values has been one of my major hurdles because it is such an abstract way to make code safer.

The point of having optional is like having a safety net in your code because it is way to prevent you app from crash. In order to how optionals come about, we need to take a step back first and observe how computers store values.

Why optionals?

The main reason why optionals exist is to prevent crashes that involves returning “nothing”. Whenever you declare a instance of a class, all the properties inside of that instance must be defined, which means that there must be a value associated with that variable you’ve just declared. Why? because there is a black and white difference between having a declare storing nothing and storing a nil. Say you are the compiler trying to obtain a value from a variable

1) As you arrive to the variable, there is absolutely nothing
2) As you arrive to the variable, there is a nil

Now, for case 1), having nothing doesn’t necessarily mean the variable contains no value because there is no information that say so. Therefore, the compiler cannot conclude what to return to the user, the compiler would say “dame, I can’t find anything here, I can’t just make up a random value because that would just be lying! and I can’t say it is empty because nothing here is telling me it is empty. Remember, when a compiler points to a variable, the variable must return some sort of information, even if it contains no value.

In case 2), as the compiler arrives to the variable, it see nil. Now, this is a complete different scenario to case 1) because the information the variable is giving to the compiler is “dude look, I have absolutely nothing here man” and the compiler would reply “sweet, I’ll just tell the user there is nothing here (or in other used nil). The point is that in case 1), there is no information that is telling the compiler that the variable contains nothing, therefore crashes the program. On the other hand, in case 2), the variable contains a nil, which is letting the compiler know that this variable does in fact contains nothing.

Let’s put this into context. Let’s say you are a event manager and you have a class that manage events and stores it a history that looks something like this,

class EventManagment {
   var eventCost: Int = 0
   var ticketPrice: Int = 0
   var numberOfPeopleAttended: Int?
}

In the very early stages of event management, you absolutely sure the you will be putting a price on the tickets and obviously getting the stage ready and having personnel will cost money, therefore, you can put in a default value, or in technical term, a sentinel value. Now, at this stage, practically speaking, all your properties have been properly declared

Notice there is a variable called numberOfPeopleAttended (empathize the past-tense there). As an event manager, how can you know how many people attended to your event when the event hasn’t even started? You might think “Well, let’s put in a sentinel value of 0, problem solved!”Well, yes but think about this, what if somehow a function accessed that variable and it will return 0, that is provide false information because that is only a “placeholder”. Saying it is zero and saying it is an optional is two different thing. One is saying “nope, nobody attended you lame gig” and second is “Look, I still having received a value yet, leave me alone!”

Optional chaining

There are two “types” of optionals, one is declared with an question mark (?) and one is declared with an exclamation mark (!) or the implicit optional.

Now, the difference is this, if you declare the (?) optional, you are saying that this value will return either a value or nil, but if you declare it with a (!), you are saying “Look, I know I have nothing at the moment (not even a nil), but I will guarantee you (the compiler) that when you access me in the future, I will have a value.

You might think “Well, what is the difference then?”. It all comes down to ease to coding. let me explain.

When you try to access an optional, say you are printing to the console, you will notice the optional text attached to that value, that is because although there is a solid value in there, but because of the nature of that property (say numberOfPeopleAttended) can always revert back to nil. In order to “extract” or unwrap the value, you need to use optional chaining. Consider the following:

class EventManagment {
    var numberOfPeopleAttended: Int?
func printThisOptional () {
if let trueValue = numberOfPeopleAttended {
print("There is \(trueValue) people attend, yay my gig is not lame after all!")
} else {
print("The event hasn't even started")
}
}
}
let bobTheEventmanager = EventManagment ()
bobTheEventmanager.printThisOptional() //console output: "The event hasn't even started"

​The optional chaining part is the if let syntax, it is saying “say if there is a solid integer (or if the variable is not nil) inside of this variable numberOfPeopleAttended, please put that value into this variable called trueValue. Pay attention on what you are doing here, you are extracting the value from an optional and putting it in a non-optional variable. Therefore, what that means is the console output won’t have the optional text attached to it.

Now, Bob the event manager is anxious and decided to peek inside to see how many people attended without realizing the event hasn’t even started. Being an intelligent coder like yourself, you have just prevented the program from crashing by having the optional chaining. The if let syntax is saying “Hey, if there is a value there, print how many people attended. If not, print the event hasn’t even started.”

You might be thinking, “Well, then what is the point of having a variable declared with an exclamation mark?”. A valid question indeed, people use implicit options so that every time you access that variable, you don’t have to use optional binding. The point here is, if you are absolutely sure that this variable will contain a value and you are not ready to give to the use, there is no point declaring it as a (?) optional because you know there is going to be a value. Having a (!) optional is like saying “Dude I promise I will give you a value later time man, don’t crash on me please!”

Well, why don’t we just use the (?) optional all the way? You absolutely sure can! but you will have a lot of if let statements in your code and it will affect readability of your code.

Conclusion

I hope I made optionals less scary for you and actually see the enormous benefits of using optionals. Stay tuned to my part two as I dive deeper in this topic and show you more advance uses with optional by sharing my real code base with you where optional had help me to write clean code.

Leave a comment if you are confused and follow me to get notified of upcoming swift related blogs!

Thanks

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.