Optional Chaining

Like optional binding, optional chaining provides a mechanism for querying an optional to determine whether it contains a value. One important difference between the two is that optional chaining allows the programmer to chain numerous queries into an optional’s value. If each optional in the chain contains a value, then the call to each succeeds, and the entire query chain will return an optional of the expected type. If any optional in the query chain is nil, then the entire chain will return nil.

Let’s begin with a concise example. Imagine that your app has a custom error code for some reason. If you encounter a 404, you actually want to use your customized error code instead. Afterward, you will want to add some ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.