Xcode

To express the possible absence of a variable’s value in Swift, we need to use optionals. A regular variable is declared in the following way:

var i: Int = 123

While an optional Int is declared like this:

var j: Int? = 123

What we are able to do with the optional Int, as opposed to the regular Int, is to assign nil to it:

j = nil

Here, nil expresses the absence of a value.

A simple example of the usefulness of nil can be seen here:

var possibleNumber = "123"
var convertedNumber = Int(possibleNumber)

possibleNumber is inferred by Swift to be a String, while convertedNumber is inferred to be an optional Int. It becomes an optional Int due to the constructor’s signature. It returns nil when the supplied String cannot successfully be converted to an Int.

We can then use an if statement to find out if the variable contains a value or not:

if convertedNumber != nil {
    print("My number is \(convertedNumber).")
}

However, the above piece of code will print:

My number is Optional(123).

When we are sure that the variable contains a value, we may force unwrap its value by appending an exclamation mark to where the variable is being used:

if convertedNumber != nil {
    print("My number is \(convertedNumber!).")
}

The value in convertedNumber will now be unwrapped, and the following string will be printed instead:

My number is 123.

Returning to the declaration of an optional Int:

var k: Int? = 123

Here, Int? is a short form of Optional<Int>. These two are therefore equivalent:

var k: Int? = 123
var k: Optional<Int> = 12

To explicitly wrap a value, use the function Optional.some(...):

k = Optional.some(42)

Note though that by simply assigning an Int to k will implicitly wrap it.

Lastly, another way to assign nil to k is by assigning Optional.none to it:

k = Optional.none

Read more about optionals, nil, wrapping, unwrapping, etc, on: