How to use Swift optionals

In Swift, optionals, represented by the keyword Optional, handle the absence of a value.

An optional has a default value of nil. It is used to set a variable or constant to contain no value in it.

An optional is a value on its own and can be declared by appending the (!) or (?) character to the data type being declared.

When an optional contains a value, it returns the keyword Optional and the value in parentheses.

Example 1

var sample1: Int?
print(sample1)

Output

nil

The example above demonstrates how to declare an optional in Swift. A variable was declared and an optional type was initialized using the ? character.

Since no value was assigned to the variable, the print statement returned nil.

Example 2

var sample2: Int? = 3
print(sample2)
print(sample2!)

Output

Optional(3)
3

In the code above, an optional of type Int was declared and assigned a value of 3. Since a value was assigned to the variable, it will have a return value of the form Optional<value>.

The second print statement unwrapped the optional and returned the value assigned to the variable.

This type of unwrapping method should only be used if it is certain that the optional will have a value when accessed.

Example 3

var sample3: Int! = 5
print(sample3)

Output

5

In the example above, an unwrapped optional was created with the Int! character. It automatically unwraps the value within the variable.

A fatal error will occur if no value was assigned to the variable.

Free Resources