Tuesday, July 19, 2022

Confusing Swift Evaluation Order

June Bash:

didDelete?(deleteItem(Item()))

[…]

This was surprising to me because i was thinking the order of operations would be:

  1. Evaluate function parameters
  2. Pass parameter into function if available

But instead it acts more like an @autoclosure.

It’s also confusing to me because in Objective-C the arguments are evaluated when the receiver is nil.

Dimitri Racordon:

print(whole.describe(whole.insert("Bar")))

John McCall:

Swift uses a strict left-to-right evaluation order in most situations. In this case, that causes the value of whole to be copied before the other arguments to describe are evaluated

As with the first example, splitting the code into multiple lines changes the behavior.

We’ve considered changing the evaluation of this so that self is not evaluated by copy but instead by immutable borrow, which in this case would cause this code to not compile due to an exclusivity error when the variable is modified while being immutably borrowed.

Previously:

Update (2022-08-29): See also: Slava Pestov.

Comments RSS · Twitter

Leave a Comment