Hi All!
(Please let me know if that was already discussed. Searched, found nothing related to such proposal.)

(TLDR: Suggest to change successor() method for Int values to follow default Swift rules for integer overflow. Probably some kind of successorWithOverflow could be introduced to use when needed)

Swift protects(trying to protect) us from Integer overflow problem, i.e. when we want to do this:
let i : Int8 = Int8.max
let k : Int8 = i + 1
, we will have run-time error on second line. Swift protects us from using (most likely) unexpected negative value (-128) for <k> variable in this case.

I believe this is really great and prevents our code from undefined behavior and some security problems. When we adds something to our Int variable in most cases we presume(and create next code with that presumption) that in result we have a bigger value in our variable. Not smaller and not negative(in case of signed Int).

If we really needs Integer overflow in our code(for example for some math), we use special operator explicitly:
let k = i &+ 1
and in this case we'll have -128 in <k> with no errors.

But. .successor() .predecessor() methods for Int values do not follow these rules for overflow situations. I.e. :
let i : Int8 = Int8.max
let k : Int8 = i.successor()
- is OK for current Swift compiler. We have i==127 and k==-128, no run-time error.

I'm totally confused in this case. No explicit 'marker' to allow integer overflow. I don't expect to have (-128) in k, I'm calling successor() to get next mathematical value for <i> and (-128) is not next value for (127).

Even worse. In Swift 3.0 we have no ++ operator. You can find that often .successor/.predecessor are recommended as replacement for ++ operator. I.e. i++ => i.successor(), I believe that many will choose this form over i += 1 or i + 1. And in this case we lose our integer overflow protection from Swift.

Suggestion is: change .successor/.predecessor for Int values to follow overflow rules and probable introduce some .successorWithOverflow/.predecessorWithOverflow if one need them in code.

Please let me know what do you think about this suggestion. Thank you.

P.S. Sorry for my English.

(Btw, I personally totally disagree with the chosen solution regarding removing ++/--, I believe that we should leave ++ and -- as form of i += 1 code. I.e. only as assignment for variable, drop all other variants of using ++ and --. And i += 1 is not just 1 char longer than i++ : in first case you have to press 4 different keys/combinations and just one(the same twice) in second case.
Just personal opinion :-) )

Vladimir.S
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to