Typesafe numeric typealiases


This package contains three generic types UnsignedValue<Storage, Unit>, SignedValue<Storage, Unit>, FloatingValue<Storage, Unit>. These can be used to implement typesafe numeric values so that you can't accidentally add two values with different types (Units). The Storage parameter is used to specify the backing arithmetic type (signed, unsigned, floating respectively) for each value. The Unit parameter is a phantom type, used for compile time type checking of the units.


Use Swift Package Manager.

import PackageDescription

let package = Package(
    name: "Phantomlike",
    dependencies: [
      .Package(url: "", majorVersion: 1)


import Phantomlike

struct FrequencyUnit { }
struct TimeUnit { }

typealias Hertz = UnsignedValue<UInt16, FrequencyUnit>
typealias Second = UnsignedValue<UInt16, TimeUnit>

let s: Second = 10
let hz: Hertz = 20

print(hz + hz) /// => Hertz(40)
print(s + hz) /// => compiler error

Other considerations

Note that the compiler will let you add a typealias and a literal of the Storage type. E.g.

print(hz + 10) /// => 30 as 10 is automatically converted


let a = 10
print(hz + a) /// type error

This should not be an issue but watch out for it.


  • Swift Tools 4.0.0
View More Packages from this Author


  • None
Last updated: Mon Jan 30 2023 14:37:24 GMT-0500 (GMT-05:00)