Practical Swift for iOS Developers: Optionals

What are optionals?

Swift does not have a “null” data type as found in other programming languages. Swift instead uses optional syntax to describe a variable (or constant) that may or may not have a value. If the optional variable (or constant) does not contain a value, it is known to be nil, which is how Swift represents a ‘valueless’ state. In this way the nil value can be used in the same manner as null in other languages. Optional variables are generally referred to as ‘optionals’.

Why use optionals?

Using optionals in your code can prevent crashes in your app. A common cause of app crashes is when the app attempts to retrieve a value that doesn’t exist. Using optionals helps the app to understand more precisely whether a property’s value exists or not, and then, how to handle it.

Where are optionals used?

Optionals are used anywhere that a value may be absent. Variables, constants, and function return type declarations are most common places where they’re used.

func printFullName(firstName: String, middleName: String?, lastName: String) {
// ...

How to declare optionals?

This is how an optional String variable is declared:

var middleName: String? = "David"
var age: Int?
age = 25
var age: Int? = 25
age = nil

Using Optionals: ‘unwrapping’

Forced Unwrapping

if middleName != nil {
print("You middleName is: \(middleName!)")
if let middle = middleName {
print("Your middle name is: \(middleName)")
} else {
print("You don't have a middle name")
if let middleName = middleName {
// ...

Guard Let statement

If access to the unwrapped variable is needed outside of the if-block, an alternative is to use the ‘guard’ statement:

Nil-Coalescing Operator

A fourth way of unwrapping an optional is by using the ‘nil-coalescing operator’, which sounds complicated, but isn’t. It can be thought of as being shorthand syntax for writing an if- else statement; but assigning a default value in the ‘else’ statement:

Full Stack React Native & iOS Developer