swift-numerics
swift-numerics copied to clipboard
Pitch: Defining custom number types integers with bound ranges
It would be great to be able to work with (brand new shiny big) binary integers and using these to define bounded number types. Number bounded by range, e.g. a BigInt bound from -273 to infinity, representing Kelvin.
I've given an attempt to do this in my SPM Package "DelTal".
/// `BUNCInt` is short _B_ound _U_nsigned _N_amed _C_ategorized _Int_eger
public typealias Kelvin = BUNCInt<NoBound<BigUInt>, KelvinName, Temperatur>
public struct KelvinName: IntegerName {
public static let nameOfInteger = "Kelvin"
}
public struct Temperatur: IntegerCategory {
public static let nameOfCategory = "Temperature"
}
public extension Kelvin {
enum Water {}
}
/* Verbose (needed) syntax for: `extension Kelvin.Water` */
public extension BUNCInt.Water where Name == KelvinName, Category == Temperatur {
static var meltsAt: Kelvin { .init(magnitude: 273) }
static var boilsAt: Kelvin { meltsAt + 100 }
}
It allows for expressive and safe wrapping of primitives according to Object-Calisthenics rule #3, and fits perfectly with Swift philosophy of safety.
It would really be amazing if developers were able to get compile-time errors inline, just like, defining this overflowing UInt8 yields a compile-time
let uint8: UInt8 = 1337
Integer literal '1337' overflows when stored into 'UInt8'
Being able to get that for custom defined integer types (or typealiases) would be... awesome!