Swift Programming Tutorial: Optional Chaining

Quickly Understand Swift Optional Chaining

Arc Sosangyo
3 min readNov 15, 2024
Photo by Jose Fontano on Unsplash

This article is part of my Swift Programming Tutorial series.

To keep this tutorial short, I’ll assume you already have a basic foundation in Swift programming, especially with concepts like optionals and instances, such as classes.

Think of optional chaining as the language’s polite way of checking if a value is there before barging in and using it.

Picture this: optional chaining is like knocking on a door before entering a room. Imagine you have a friend named Bob who might live in an apartment, and Bob might have a pet cat. But maybe he doesn’t have an apartment at all, and if he does, maybe he has a dog or, no pet at all. With optional chaining, you can ask Swift if Bob has an apartment and if that apartment has a dog — without risking an awkward moment if either one’s missing.

The Syntax

Here’s the magical part: you just use a question mark (?) to keep things civil. Here’s what that might look like:

let catNameInBobApartment = bob.apartment?.cat?.name

Let’s break this down like we’re investigating a mystery. Here’s what Swift is doing:

  1. “Does Bob have an apartment?” Swift checks…

--

--

Arc Sosangyo
Arc Sosangyo

Written by Arc Sosangyo

Arc is an iOS Dev and app publisher, a former IT manager who transitioned to iOS engineering, and a big fan of AI, coding, science, history, and philosophy.