Optionals in Swift

At the moment I’m spending some of my free time learning Apple’s new language Swift. Since optionals are one of the key features in Swift and are not easy to grasp I thought about writing about them as my first post since writing about something helps you gain a deeper understanding about something. So let’s get right to it.

Generally said an optional is a variable which can (and might) be nil. A “normal” variable in swift is not allowed to be nil at any point.

An optional is visually noticible because it is declared with a ? at the end of its type.

// error
var text: String = nil
// works since it is an optional
var text: String? = nil

To summarize: You will be involved with optionals when dealing with nil in Swift.


Since e.g. a String optional is not exactly the same as a normal String the usage of the optional is different compared to non-optionals.

To access the value of an optional you have to unwrap it. Unwrapping works using an exclamation mark !.

var num: Int? = 5
// print unwrapped value
print(num!)

Since an optional can be nil you should check the optional before unwrapping it

// throws an error
var num: Int?
print(num!)
// check before unwrap
// func “getText” returns a string optional
var text: String? = getText()
// printing unwrapped string
if text != nil {
print(text!)
}

Since the if != nil construct is so often-used a special construct for this exists which is called if-let

// if-let does not need an exclamation mark
if let text = getText() {
print(text)
}

To summarize: To access the value of an optional you have to unwrap it. For the safe unwrapping of optionals the if-let construct exists.


Swift provides a cool process called optional chaining. Imagine the following situation:

class House {
var apartment: Apartment?
}
class Apartment {
var owner: String?
}

In case you have an instance of a house object you would have to use the following code in many programming languages to safely access the apartment owner

if (house.apartment && house.apartment.owner) {
print(house.appartment.owner)
}

Swift optionals enable you to do this more elegantly

// print will only get executed if none of the attributes is nil
if let person = house.apartment?.owner {
print(person)
}

To summarize: Optional chaining safely enables you to execute a certain piece of code only if all optionals in the chain were not nil.


Now let’s make an example where optionals might be used in Swift.

Let’s say we want the simple (but needless) program which first divides two numbers and then doubles the result. Since the input numbers might change we want to make sure that nobody divides by 0 to make the program throw an error.

For this we will write a simple function

func divide(num1: Int, num2: Int) -> Int? {
if num2 != 0 {
return num1 / num2
}
else {
return nil
}
}

Now we can use this function as follows

var num1 = 10
var num2 = 5
if let result = divide(num1, num2: num2) {
// double the result
print(result * 2)
end

This way using optionals our program is safe of the division by zero error.