rockbruno
(Bruno Rocha)
March 9, 2018, 1:24am
1
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.
xwu
(Xiaodi Wu)
March 9, 2018, 5:59am
3
Agree. In fact, there's a Swift bug tracking this issue, filed by @dabrahams I believe.
xwu
(Xiaodi Wu)
March 9, 2018, 9:23am
5
That may be an interesting topic to discuss, but let's keep this thread focused on the main poster's topic, overflow assignment operators.
rockbruno
(Bruno Rocha)
March 9, 2018, 1:01pm
6
Thanks guys, I've located @dabrahams 's ticket. Here it is.
ctxppc
(Constantino Tsarouhas)
March 9, 2018, 1:03pm
7
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
Nevin
March 11, 2018, 12:35am
11
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...
Nevin
March 11, 2018, 1:58am
13
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
rockbruno
(Bruno Rocha)
March 11, 2018, 11:23am
15
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.
Ben_Cohen
(Ben Cohen)
March 11, 2018, 1:11pm
16
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