Optional chaining with operators

Yes, and I wrote a reply to you a year ago with the answer. Namely, try hoisting cannot be expressed in terms of Swift precedence but looks to whether the neighboring operator is an assignment operator.


Even if we didn't have any special rules for assignment operators, you still couldn't just allow optional chaining for non-assignment operators and expect things to go well. Recall that a chain implies that there are multiple "links":

struct Foo { var bar: Int? }
var foo: Foo? = Foo(bar: 42)

print(foo?.bar == nil)           // false
print(type(of: foo?.bar == nil)) // Bool
foo = nil
print(foo?.bar == nil)           // true

In other words, using parens to indicate order of operations, we have (foo?.bar) == nil.

Here's what happens when you allow optional chaining:

struct Foo { var bar: Int? }
var foo: Foo? = Foo(bar: 42)

precedencegroup _ComparisonPrecedence {
  assignment: true
  associativity: none
  lowerThan: NilCoalescingPrecedence
  higherThan: LogicalConjunctionPrecedence
}
infix operator == : _ComparisonPrecedence

print(foo?.bar == nil)           // Optional(false)
print(type(of: foo?.bar == nil)) // Optional<Bool>
foo = nil
print(foo?.bar == nil)           // nil

In other words, using parens to indicate order of operations, we have instead (notionally) foo?(.bar == nil). This is a totally different expression than the status quo shown above; users (or, at least, any user who's written any code already) actually wouldn't want this chaining for non-assignment operations.

5 Likes