Swift Optional Chaining With Examples

Swift Optional Chaining is a very useful feature. Optionals are a type in Swift that wrap primitive types and are typically used for preventing null values. For more details on Optionals refer this tutorial before proceeding ahead.

Swift Optional Chaining

Optional Chaining is the process of chaining calls on optional values such that it handles the unwrapping gracefully and concisely without giving runtime errors. As the name says, it chains multiple queries together.

But the same thing is achievable using if let,guard let and implicit unwrapping too.

What’s the need for Optional Chaining then?

Let’s look at an example in Playground first without bringing Optional Chaining.

Without Optional Chaining

Let’s assume we have the following classes:

Every class contains an instance of the below class. All instances are defined as optionals.
College class holds an array of Discpline class objects.

Let’s instantiate each of these classes.

Using Implicit Unwrapping
Let’s get and retrieve properties and functions from the classes using implicit unwrapping (!).

This looks okay. But we know from the Optionals in Swift tutorial that implicit unwrapping can lead to runtime crashes since it unwraps the optional without checking if it’s nil or not.

In the above code, if we set myStudent as nil, it’ll lead to a CRASH.

Let’s try using if let/if var.

Too much of nesting! And that too just to set values and print the result in a very basic code with hardly a few properties in each class.

This is inefficient.

Using guard var
Let’s do the same using guard var.

This is better than if var but still too many conditional checks. Implicit wrapping was concise and crisp but dangerous since it didn’t check the optional value before unwrapping.

This is where Optional Chaining comes to our rescue.

It’s an alternative and better form of forced unwrapping.

In optional chaining, we just need to replace !. with ?..

How does Optional Chaining work

Optional Chaining is done over optional values. It returns the desired value wrapped as an Optional. If the optional is nil, it returns an Optional(nil). Optional Chaining always gives you an optional thereby eliminating the chance of runtime crashes.

Hence two things:

  • If the type that’s been retrieved through Optional Chaining is not optional, then after the optional chaining is done, it becomes optional.
  • If the type was already optional, it’ll stay optional only. It’ll not get nested like Optional(Optional(String)).

Implementation With Optional Chaining

The below code has optional chaining implemented.

Now printDetails() was defined to return a String.

Does it?
NO.

It returns an Optional(String) since the Optional Chaining wraps the returned value with an optional.

Accessing Subscript calls through optional chaining

Change the Discpline class to:

Thanks to subscripts we can get rid of the discpline object invocation.

Note: When accessing a subscript on an optional value through optional chaining, you place the question mark before the subscript’s brackets, not after. Hence we’d done college?[0]. It gets the first discipline.

This brings an end to this tutorial. You can download the Swift Playground file from the below link.

OptionalChaining.playground.

Reference: Apple Docs

By admin

Leave a Reply

%d bloggers like this: