# Optional chaining with operators

**URL:** <https://forums.swift.org/t/optional-chaining-with-operators/55049>\
**Category:** Using Swift\
**Created:** [February 2, 2022, 4:16pm UTC](https://forums.swift.org/t/optional-chaining-with-operators/55049 "2022-02-02T16:16:21Z")\
**Posts on this page:** 1\
**Showing post:** 13

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [February 3, 2022, 7:43am UTC](https://forums.swift.org/t/optional-chaining-with-operators/55049/13 "2022-02-03T07:43:34Z")

</div>

> [@Nevin](#):
>
> Does the `assignment` field of a precedence group do anything _other_ than enable optional chaining for operators?

Yes, and I wrote a [reply](https://forums.swift.org/t/exponentiation-operator-and-precedence-group/44895/45) 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.

* * *

> [@Nevin](#):
>
> If not, then making this work seems fairly simple. We could do away with the `assignment` field entirely, and make all operators work with optional chaining. Or at least, we could make the _default_ be to allow optional chaining.

_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":

```swift
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:

```swift
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.

---

_[View the full topic](https://forums.swift.org/t/optional-chaining-with-operators/55049)._
