Optional Chaining in Swift

because the result of optional chaining is always optional.

For example, we can use if statement to check if it’s possible to call the printNoOfClasses() method even when the method doesn’t define any return value.

As we know that this method call through optional chaining will return optional value if successful, we can compare the return value from printNoOfClasses() call against nil to know if the method call is successful or not.

Let’s see the code snippet which demonstrate this.

Accessing Subscripts Through Optional ChainingAlong with calling methods and accessing properties, optional chaining can also be used to try to retrieve and set a value from a subscript on an optional value, and to check whether that subscript call is successful.

This can be explained in better manner with following example.


clg is currently nil so the subscript call fails.

Even if we try to set a new value through a subscript with optional chaining likejohn.

clg?[0] = Room(name: “Classroom-1”)As clg is currently nil, this subscript setting attempt also fails .

We can use optional chaining to access the actual items in the classes array if we create and assign an actual College instance to john.

clg, with one or more ClassRoom instances in its classes array.

Accessing Subscripts of Optional TypeIf a subscript returns a value which is optional, for example, key subscript of dictionary type in Swift, the values of array or dictionaries which is declared with an optional type can be modified.

To chain subscript on its optional return value, place a question mark after the subscript’s closing bracket.

To understand this, take a look at following code snippet.

Linking Multiple Levels of ChainingOne interesting fact about linking multiple levels of optional chaining is, we can add many levels to drill down to properties, methods or subscripts but multiple levels of optional chaining do not add more levels of optionality to the returned value.

Now you know multiple uses of optional chaining in swift.

So why don’t you open playground and start playing with it to get good commend on it?.

. More details

Leave a Reply