Confusing Swift Evaluation Order
didDelete?(deleteItem(Item()))[…]
This was surprising to me because i was thinking the order of operations would be:
- Evaluate function parameters
- 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
.
print(whole.describe(whole.insert("Bar")))
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 todescribe
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.