Associative arithmetic operation order matters in Swift?

First, a minor note: you're talking about associativity, not commutativity.

  • An operation is commutative if a OP b == b OP a for all a and b.
  • An operation is associative if a OP (b OP C) == (a OP b) OP c for all a, b, and c.

Trapping arithmetic is commutative, because there are no intermediate results. It is not associative, because the values of intermediate results change under reassociation.

Ok, onward!

This has been discussed extensively in the past. @Joe_Groff and I and a few other people suggested that Swift should use a variant of the AIR model about a decade ago, which would result in behavior like you suggest for all arithmetic, not just literals. The window for such major changes to basic operations in Swift has probably passed, though.

We've also talked about optimizations that would allow the compiler to relax precise traps in integer arithmetic. This has some benefits, but also impairs predictability and the ability for programmers to reason about the system, and so is maybe undesirable.

As for literals specifically, it's definitely undesirable to introduce language changes that make integer literals behave differently from integers, because it interferes with people's ability to understand the system, even if it's sometimes useful. That ship already sailed--there are lots of ways in which literals don't act like integer values already--but we can refrain from making it worse.

17 Likes