Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 146 ยท Structures, Classes and Enums

Optional Chaining in Depth

Master Swift optional chaining - reading through nested optionals, calling methods and subscripts, assigning through a chain, short-circuiting, flattening results and when to unwrap instead.

Real data is full of "maybe". A person may have a home, the home may have an address, the address may have a street number. If each link in that chain is an optional, then getting the street number looks like a staircase of if let statements. Optional chaining is Swift's shorthand for walking such a chain: you put a ? after each optional and the whole expression stops safely at the first nil.

You met the basics in Optionals and the helpers in Optionals in Depth. This lesson is about chains that run through your own classes and structs: reading properties, calling methods, using subscripts and, less obviously, assigning through a chain. It explains what type you get back, when code does and does not run, and when a different tool is a better choice.

The model: Person, Residence, Address

We will use one running example. A Person may have a Residence. A residence has rooms and may have an Address. Every "may" is an optional:

Swift A chain of optional properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The expression ada.residence?.address?.street is read left to right. If ada.residence is nil, the rest of the chain is skipped and the whole expression is nil. If the residence exists but its address is nil, evaluation stops there. Only when every link has a value do we reach street.

Notice the type of the result. street is a plain String, yet the chain gives String?. That is the first rule of optional chaining: whatever the end of the chain returns is wrapped in an optional, because the chain may have stopped early. The last line prints Optional(12) and not Optional(Optional(12)), which leads to the second rule.

Results are flattened, never doubly optional

number is already Int?. If chaining wrapped it again, you would have Int??, a type nobody wants. Swift flattens it: a chain that ends in an optional produces one level of optional, no matter how many ? are in the chain.

Swift The result type of a chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

street has type Optional<String> and number has type Optional<Int>: one layer each. You can then consume the result with if let, guard let, or ?? like any other optional. For instance, p.residence?.address?.street ?? "unknown" gives a plain string with a fallback.

What the compiler asks of you: the question mark is required

If a value in the middle of the chain is optional, you cannot just write .. The compiler insists that you decide what happens on nil.

Swift Forgetting the question mark (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is value of optional type 'Residence?' must be unwrapped to refer to member 'rooms' of wrapped base type 'Residence', followed by fix-it notes: chain with ? to make the result optional, or force-unwrap with !. The first option is nearly always the right one.

The force-unwrap version is person.residence!.rooms. The ! means "I promise there is a value; crash if I am wrong":

Swift Force unwrapping nil in a chain (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first print appears, then the program traps at the ! and after never prints. The optimized build used here ends the process with a SIGILL signal and a backtrace instead of the message you would see in a debug build (Fatal error: Unexpectedly found nil while unwrapping an Optional value). Use ? when absence is normal, and use ! only where a nil would mean a bug in your own code that you want to stop on.

Methods and subscripts through a chain

Chaining is not limited to properties. You can call methods and use subscripts at any point, always with ? before the dot or bracket:

Swift Methods and subscripts in a chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first block runs when residence is nil and every line prints nil; the second block, after we create a residence, prints real values wrapped in Optional(...). Pay attention to the subscript syntax: person.residence?[0], with the ? directly before the bracket. And look at the last line. The chain continues past the subscript, through .name and into the method .uppercased(), and it is still just one optional result at the end.

Methods that return nothing

A method that returns Void also gets wrapped. Calling person.residence?.printNumberOfRooms() has type Void?, which tells you whether the call happened. That makes a neat test:

Swift Did the call happen?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first call is skipped entirely (nothing is printed by the method), so the optional result is nil. The second call runs the method, which prints, and returns (), which is not nil. You will not need this trick often, but it explains why a call through a chain is an expression with an optional type. For a more readable version, if let residence = person.residence { residence.printNumberOfRooms() } does the same thing.

Assigning through a chain

You can also write at the end of a chain. If any link is nil, the assignment silently does nothing. And, importantly, the right-hand side is not even evaluated in that case:

Swift Assignment through a chain short-circuits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In the first attempt, makeStreet() never runs: the message does not appear before --- after first attempt. This is called short-circuiting, and it matters when the right-hand side is expensive or has side effects (network calls, logging, counters). Once the chain is fully populated, the function runs and the street changes. Note that assignment through a chain only changes values that already exist; it never creates the missing residence or address for you. If you want to create them, assign them explicitly like person.residence = Residence().

Chains and value types

Chains work on structs too, and writing through a chain modifies the stored value in place:

Swift Writing into a struct inside an optional

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

stored?.recentFiles.append(...) mutates the struct inside the optional without unwrapping it by hand. If stored is nil, the call is skipped. For var optionals this is the most compact way to update a value if it is present.

Combining chains with other tools

Optional chaining is most useful when combined with the rest of the optional toolkit:

Swift Chains with ??, if let and map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The loop with ?? gives every person a printable street. The if let version binds the final value, so the body only runs when the whole chain succeeded. compactMap over the people collects just the existing streets, which is how you turn "a list of maybes" into "a list of values". The last statement shows Optional.map: since address is Address?, .map runs its closure only when there is an address, and chaining keeps going before it.

Pitfalls and good habits

  • A long chain is a design smell. a?.b?.c?.d?.e couples your code to the shape of four types (the "Law of Demeter"). Often the owner of the data should offer a method, such as person.streetName, that hides the chain.
  • nil has several meanings. A chain that returns nil cannot tell you which link was missing. If you need to report that precisely, unwrap step by step with guard let and give different errors.
  • Reference types change underneath you. With classes, the chain reads the current state each time. If other code changes residence between two chains, the results can disagree. Take a local copy (if let residence = person.residence) to look at one consistent snapshot.
  • Do not use ! as a shortcut for a long chain. A crash from a!.b!.c! tells you only "found nil" and not where.
  • Chains inside try? flatten as well. try? parse(x)?.value produces a single optional in modern Swift, not a nested one.

If you find yourself writing if x != nil { x!.something }, replace it with if let x { x.something } or x?.something. The compiler can check those forms; it cannot check the manual !.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of person.residence?.address?.number when number is declared as Int??

    Optional chaining flattens: the result is always a single optional, even when the final property is already optional.
  2. 2. What happens to person.residence?.address?.street = makeStreet() when residence is nil?

    The chain short-circuits at the first nil. The assignment does nothing, and the right-hand side is never evaluated.
  3. 3. How do you write optional chaining on a subscript of an optional value item?

    Put the question mark directly before the brackets: item?[0]. If item is nil, the subscript is not called.
  4. 4. Which expression returns a plain String, never an optional?

    The nil-coalescing operator supplies a fallback, so the combined expression is a non-optional String. The others keep the optionality.
  5. 5. Why is a very long chain such as a?.b?.c?.d often discouraged?

    Long chains expose internal structure and cannot tell you which step failed. A method on the owning type or a stepwise guard is clearer.

Summary

  • Put ? after each optional in a chain; evaluation stops at the first nil and the whole expression is nil.
  • The result of a chain is always wrapped in one optional, and an already-optional result is flattened rather than doubled.
  • You can chain through properties, methods (a Void method yields Void?) and subscripts (value?[i]).
  • Assigning through a chain does nothing if a link is nil, and the right-hand side is not evaluated.
  • Writing through a chain works for value types too, which is handy for optional structs.
  • Combine chains with ??, if let, compactMap and Optional.map; avoid ! and avoid very long chains.

Next: Type Casting