skip to content

In Swift, what type does an optional chain like profile.manager?.avatarURL return, and how does ?? supply a fallback?

level: middleimportance: must knowfreq 75%

answer

  1. the result is always optional
  2. no extra levels of optionality
  3. one nil link skips the rest
  4. an autoclosure on the right

basics

~20 s

An optional chain always returns one level of optional: if any link is nil, the rest of the expression is skipped and the chain is nil. The ?? operator unwraps that result or evaluates its right-hand default, only when needed.

solid answer

~40 s

`profile.manager?.avatarURL` has type `String?` whether `avatarURL` is declared `String` or `String?`: chaining makes a non-optional result optional and adds no second level to an already optional one. When a `?` link finds `nil`, Swift ignores every remaining operation in that postfix expression, including evaluating method arguments, and the whole expression is `nil`. A `Void` method called through a chain returns `Void?`, which tells you whether the call happened. `??` unwraps its left operand or returns its right one; the right operand is an `@autoclosure`, so it is evaluated only when the left side is `nil`. A chain of `??` reads left to right, and the last operand decides whether the result is optional.

code

swift · 29 lines
swift
final class Employee {
    let name: String
    var avatarURL: String?
    var manager: Employee?
    init(name: String, avatarURL: String? = nil, manager: Employee? = nil) {
        self.name = name
        self.avatarURL = avatarURL
        self.manager = manager
    }
    func rename(to newName: String) -> Bool { !newName.isEmpty }
}

func expensiveDefaultName() -> String {
    print("expensiveDefaultName() called")
    return "Unknown"
}

let lead = Employee(name: "Rui", avatarURL: "https://example.com/rui.png")
let dev = Employee(name: "Ana", manager: lead)
let intern = Employee(name: "Bo")

let length = dev.manager?.avatarURL?.count            // Int?, holds 27
let renamed = intern.manager?.rename(to: expensiveDefaultName())
print(type(of: length), renamed as Any)               // Optional<Int> nil (nothing called)

print(intern.manager?.name ?? expensiveDefaultName()) // prints the call, then Unknown
print(dev.manager?.name ?? expensiveDefaultName())    // Rui, default never evaluated
let avatar: String = intern.avatarURL ?? intern.manager?.avatarURL ?? "placeholder.png"
print(avatar)                                         // placeholder.png

go deeper

for a junior

Recall that ?. returns nil instead of crashing and that ?? supplies a default value when the left side is nil.

for a middle

Explain the result-type rule, the short-circuit that skips arguments and assignments, Void? results, and the two ?? overloads with the autoclosure default.

for a senior

In review, catch side effects hidden in chained arguments, Bool? comparisons that disagree on nil, and ?? defaults that mask data that should have been reported.

for a principal

Decide where silent defaulting is acceptable, such as display text, and where a missing value must surface as an error or a log line, and make that boundary visible.

## Optional chaining in one sentence **Optional chaining** lets you reach through an optional to a property, method or subscript by writing `?` after it: `employee.manager?.avatarURL`. If `manager` holds an employee, Swift unwraps it and continues; if it is `nil`, the chain **fails gracefully** and the whole expression evaluates to `nil` instead of trapping, which is what a force unwrap (`manager!.avatarURL`) would do. Take a directory model decoded from a backend where many employees have no manager and no avatar: ```swift final class Employee { let name: String var avatarURL: String? var manager: Employee? init(name: String, avatarURL: String? = nil, manager: Employee? = nil) { self.name = name self.avatarURL = avatarURL self.manager = manager } } ``` ## The result type rule The Swift book states the rule in two halves, and interviewers check both: - If the value you retrieve **isn't optional**, it becomes optional because of the chain: `employee.manager?.name` is `String?`. - If the value is **already optional**, the chain does not make it more optional: `employee.manager?.avatarURL` is `String?`, not `String??`. - However many links you add, the level of optionality stays one: `employee.manager?.avatarURL?.count` is `Int?`. - Only the **outermost** postfix expression carries the optional type; the links in the middle are unwrapped values while the chain is running. ## Short-circuiting the whole chain When a link is `nil`, the language reference says all of the other operations in the postfix expression are ignored. In practice: 1. Later property reads, method calls and subscripts are not performed. 2. **Arguments** to a skipped method are not evaluated, so `intern.manager?.rename(to: expensiveDefaultName())` never calls `expensiveDefaultName()` when `manager` is `nil`. 3. On an assignment through a chain, such as `employee.manager?.avatarURL = loadURL()`, the right-hand side is not evaluated if the chain fails. This is a feature for performance and a trap for code that relies on a side effect in an argument. ## Void? and assignments A method with no return type returns `Void`. Called through a chain, it returns **`Void?`**, so `if employee.manager?.notify() != nil { … }` tells you whether the call ran. An assignment through a chain also produces `Void?`, which you can compare with `nil` the same way. ## The nil-coalescing operator `a ?? b` returns the wrapped value of `a` if it has one, otherwise `b`. Two standard-library overloads matter: | Overload | Right operand | Result | Typical use | |---|---|---|---| | `(T?, @autoclosure () throws -> T) rethrows -> T` | non-optional | `T` | final fallback: `?? "placeholder.png"` | | `(T?, @autoclosure () throws -> T?) rethrows -> T?` | optional | `T?` | try another source: `?? cache[key]` | Because the right operand is an **`@autoclosure`**, it is evaluated only when the left side is `nil`; the standard library documents this as short-circuit evaluation. That is why `?? expensiveDefaultName()` costs nothing when a value exists. Chained `??` operators read left to right; the first non-`nil` value wins, and the type of the **last** operand decides whether the whole result is optional. ## Chaining through subscripts and function values The `?` works on any postfix expression, not only properties: - **Subscripts**: `scores["ana"]?[0]` reads the first element of an optional array returned by a dictionary lookup, and `scores["ana"]?[0] = 95` writes through it, doing nothing if the key is missing. - **Optional function values**: a stored callback `var onTap: (() -> Void)?` is called with `onTap?()`, which does nothing when no callback is set. - **Mixing with `!`**: `profile.manager!.avatarURL` is unconditional chaining; it traps when `manager` is `nil` instead of producing `nil`. ## Chaining or binding Chaining suits a single access whose result you either use as an optional or immediately default with `??`. When you need the unwrapped value several times, or need to know *which* link was `nil`, an `if let` or `guard let` that unwraps each link reads better and gives you a place to handle each case. ## Pitfalls interviewers probe - Expecting `String??` from a chain over an optional property. - Assuming an argument with side effects still runs when the chain fails. - Ending a `??` chain with an optional operand and then being surprised the result is still optional. - Comparing `employee.manager?.isActive == true` versus `!= false`: with a `Bool?`, `nil` is neither, so the two checks disagree when the chain fails. - Hiding a real bug by defaulting with `??` where a missing value should have been reported.

  • Is a method argument evaluated when the optional chain in front of it is nil?
    No. When a `?` link is `nil`, Swift ignores every remaining operation in that postfix expression, and evaluating the method's arguments is one of them. `intern.manager?.rename(to: expensiveDefaultName())` therefore never calls `expensiveDefaultName()` when `manager` is `nil`. The same holds for the right-hand side of an assignment through a chain.
  • Why can a chain of ?? operators still produce an optional result?
    `??` has two overloads: one takes a non-optional default and returns `T`, the other takes an optional default and returns `T?`. In `a ?? b ?? c` the last operand decides which overload finishes the chain. If `c` is optional, for example another dictionary lookup, the result is still optional; end with a non-optional literal or value to get a plain `T`.

  • Chaining through two optional properties produces a double optional.
  • The default after ?? is always evaluated, so expensive calls must be avoided there.
  • If one link in a chain is nil, the remaining method calls still run with nil.
  • Optional chaining traps on nil just like a force unwrap does.
  • A Void method called with ?. returns plain Void, so you cannot tell whether it ran.