Currently, Swift Int family and UInt family have compact representations that
utilize all available values, which is inherited from C. However, it is
horribly inefficient to implement optional integers. It takes double the space
to store [Int?] than to store [Int] because of alignment.
I propose to ban the top value in Int/UInt which is 0xFFFF... in hex. Int
family would lose its smallest value, and UInt family would lose its largest
value. Top value is reserved for nil in optionals. An additional benefit is
that negating an Int would never crash.
Interacting with C/Obj-C is a major concern, but since we are already importing
some of the unsigned integers as Int which loses half the values, one value is
not such big a drawback. Alternatively, we could leave current behavior as
CInt/CUInt. Converting them to the new Int?/UInt? doesn't generate any
instructions since the invalid value already represents nil.
With optional integers improved, we could implement safe arithmetic
efficiently, or even revisit lenient subscript proposals, but they are not in
the scope of this pitch. Float/Double optionals could also be improved with the
similar idea. (Isn't signaling nan the same as nil) Nested optionals such as
"Int??" are still bloated, but I don't think they are widely used.
So what do you think? Can we break C compatibility a bit for better Swift types?
swift-evolution mailing list