Search code examples
uitableviewswiftoption-typeoptional-chaining

Optional chaining used in left side of assignment in Swift


What does it mean when optional chaining is used in the left side of the assignment statement? Will the app crash if the optional variable is nil?

e.g.

// cell is a UITableViewCell
cell.textLabel?.text = "Test"

Solution

  • Sort of like a short-circuiting && operator that stops when it reaches the first false value, optional chaining will stop when it hits the first nil value.

    So in an extreme case like container?.cell?.textLabel?.text = "foo", any of container, cell, or textLabel could be nil. If any of them are, that statement is effectively a no-op. Only if the whole chain is non-nil will the assignment happen.