Use Swift's type system to restrict values

To elaborate for those that might be confused by these numbers, this is referring back to Memory-optimal collections of Optionals. Giving up even just a single value in the Element's space allows (in principle) Optional to use that to represent nil, thus saving it from having to have a separate boolean flag and therefore unintentionally doubling the size of each Array because of the need to maintain correct alignment for Element.

Not just limited, but very small. Because defining explicit enum cases for e.g. the range of Int, would be not just comically inefficient in size (on the order of a hundred billion billion bytes of source code) but practically guaranteed to never compile (due to super-linear compile-times for enums based on their member count).

Even a more "plausible" scenario like a mere Int8-sized thing would be many kilobytes of code just for the cases, not even counting the various helper methods to convert to actual numeric values. So we're talking tens of kilobytes of source to express the notion typealias DomainSpecificInt = UInt8 where Self ~= 0...250.

And even if all of that isn't a showstopper, the ergonomics of enums for numeric values are horrible - you have to manually conform them to all the relevant numeric protocols, which is a lot of surface area (just try implementing your own FixedWidthInteger and see how many dozens and dozens of methods & properties that requires).

2 Likes