[swift-evolution] Simplified Conversion of Integer Types

John McCall rjmccall at apple.com
Tue Jan 19 20:57:42 CST 2016

> On Jan 15, 2016, at 9:51 AM, Chris Lattner via swift-evolution <swift-evolution at swift.org> wrote:
> On Jan 15, 2016, at 2:46 AM, Haravikk via swift-evolution <swift-evolution at swift.org> wrote:
>> Something that’s still an annoyance to me in Swift is conversion between different integer types, both by size and signed vs. unsigned, as many mismatches result in errors requiring either refactoring to one common type, or boiler-plate to cast the values.
> Yes, it is.
>> I’d like to propose that Swift implicitly cast values to an integer type with a larger size (so in this case there is no error as an Int64 is larger than an Int16).
> This is also my desire.
> DaveA and Max have a tentative plan to improve integer semantics in these phases:
> 1. Improve the comparison and shift operators to not require symmetry.  You should be able to do “someUInt == someInt” and get a proper value comparison.
> 2. Improve the numerics related protocols to enable writing generic code over different width types.
> 3. Introduce subtyping relationships between the integers and the floats so that we can implicit promotions from smaller to wider types.  This can either be done with a general language feature to introduce subtyping of structs/enums or by hacking it into the compiler, different folks have different opinions on how this will work, and it isn’t designed yet.
> The first two are a strong goal for swift 3, the later is "nice to have” if it fits since it is “just” sugar and there is a lot of other stuff going on.  We are also interested in introducing a proper BigInt type, but that is even “nicer to have” for Swift 3.

Random thoughts here:

Integer promotions are nice for arithmetic, but they can mask bugs for “reinterpret” style conversions.  You don’t want an Int32 to Double/UnsafePointer reinterpretation to implicitly promote to Int64; you want it to be a compiler error.  But that’s a special-case limitation that can reasonably be directly addressed on those APIs.

It's probably reasonably to have general rules that allow integer arithmetic to just promote to the wider type, but I don’t think we can do common-type promotion without special knowledge of type rank.

My understanding is that numerics people don’t love implicit promotions between floating-point types.  Float promotions and conversions are comparatively expensive, and they can introduce subtle rounding bugs; the standard advice is that programmers should be writing their code to avoid them.

Integer-to-float promotions have similar performance issues as float promotions, and IntN -> FloatN is technically lossy.


More information about the swift-evolution mailing list