Optionals are used when a value cannot be set. Think of optionals as a container, which can take either a value or nil. This gives us the ability to check whether the value is nil or not. In order to create an optional value, you will have to give it a data type followed by a question mark (?
). Before we do that, let's create a string that is not an optional. Add the following to Playgrounds:
var strNotAnOptional = "This is not an optional"
Now, let's add an optional to Playgrounds:
var strOptional:String?
In this example, we created a string optional, and, if you notice in the Results panel, it is nil. But for our strNotAnOptional
, we see This is not an optional
. Now, on the next line, let's set strOptional
equal to This is an optional
:
strOptional = "This is an optional"
In our Results panel, we see This is an optional
. Let's now print both strNotAnOptional
and strOptional
, as you will see a difference between the two:
print(strNotAnOptional) print(strOptional...