8. Optionals
So far, we have learned about the variables and constants that we always initialize with data. What about we declare a variable without any data in it and try to use it, like the following:
var myInt:Int
print(myInt)It will give us an error:

So, we cannot use a variable without initializing it, right?. Well, sort of. Swift allows us to keep the variables uninitialized. It is done using a special data structure called Optional. Optionals are declared by adding a ? at the end, like the following:
It will print the following:
First of all, nil means there is no value. It is equivalent to null in many other programming languages like Java. So we have to make sure we do not use an optional value if we haven't yet stored a value in it; otherwise, it might crash the program. Luckily, Swift handles optionals safely.
To understand the process, let's assign a value to myInt before we print it:
It prints Optional(10) instead of 10. That means, the value of myInt is wrapped with the optional data type. By wrapping the value with Optional, Swift makes us unwrap the value before we use it. While unwrapping, we can detect if the unwrapped value is nil or not and take care of nil before we use it in the program to prevent crashes. There are three ways of unwrapping them.
If-let
Guard-let
Forced
We will talk about if-let and forced for now. Eventually we will learn about guard-let.
If-let
We can unwrap an optional value using if-let block. To unwrap myInt we can write:
It prints:
So here, we are binding the optional value by assigning it to unwrappedMyInt constant. If a value is present, the unwrappedMyInt will hold the unwrapped value from the optional myInt; else, we have to handle the condition where we have nil in our optional.
Forced
Another way of unwrapping an optional is using forced unwrapping. We need to put a ! after the optional variable to unwrap the value from it forcefully. For example, we can write:
Which will unwrap the value of myInt forcefully, even if it is nil.
So you should refrain from using ! unless you are absolutely sure that the value is not nil.
The usage of optionals is very common in Swift, and eventually, we will have more examples down the road.
Source code
Last updated
Was this helpful?