[Pitch] Overflow assignment operators (&+= &-= &*=)

I occasionally have to deal with overflow operators, and I will always instinctively attempt to an operation with an assignment operator - just to be reminded that they do not exist. Luckily, writing them as an extension is trivial.

However, since all arithmetic and bitwise operators possess an equivalent assignment operator, it feels right to me that overflow operators should also have them.

//A possible protocol example
public static func &+=(lhs: inout Self, rhs: Self) {
    lhs = lhs &+ rhs
}

Looking forward to see what you think about this.

14 Likes

+1, seems like an obvious hole.

Agree. In fact, there's a Swift bug tracking this issue, filed by @dabrahams I believe.

That may be an interesting topic to discuss, but let's keep this thread focused on the main poster's topic, overflow assignment operators.

Thanks guys, I've located @dabrahams 's ticket. Here it is.

Interesting idea, but I’d prefer &&= and ||= instead, for consistency with the other assignment operators.

Does this even need a formal review since it's ticketed as a bug and seems fairly uncontroversial?

1 Like

I think it can be considered a bug fix. Please email the swift core team mailing list to get an official opinion though.

&= is the better spelling here IMO. The && operator is short circuiting, and &&= wouldn't be.

-Chris

Out of curiosity, why not? I would expect:

x &&= foo()

to be identical to:

x = x && f()

so when x is already false then f() would not be called.

Moreover, if “&=” for Bool does *not* behave that way, then it looks like an attractive nuisance. People will write:

someValue.isFoo &= foo()

because it is shorter than:

someValue.isFoo = someValue.isFoo && foo()

but then foo() will be called 100% of the time, a potential performance pitfall.

1 Like

Ok fair point, if we are going for completeness and full generality, then I guess we have to support both the strict and lazy forms...

Do we though?

The “&” operator is only available for Int types, not for Bool. The standard library does not support writing “true & false” because no such operator exists.

Good point, you're right again. We still have to support &=, but only defined on integer types, just like we currently do. Thanks for clarifying.

-Chris

I implemented the operators here for who's interested, but it seems like we'll need a formal review indeed. Will create one shortly if necessary.

I agree with Chris, I think this can be considered a bug and not something we need a full review for. For + - and * at least.

3 Likes