Swift Package Index


Typesafe numeric typealiases


  • The latest stable release is 1.0.0. Released 3 years ago.
  • The last commit to master was 3 years ago.

Swift Version Compatibility

  • 1.0.0 and master
    5.3
    5.2
    5.1
    5.0
    4.2
Full build results

Platform Compatibility

  • 1.0.0 and master
    iOS
    macOS(Intel)
    macOS(ARM)
    Linux
    tvOS
    watchOS
Full build results

Phantomlike

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.

Installation

Use Swift Package Manager.

import PackageDescription

let package = Package(
    name: "Phantomlike",
    dependencies: [
      .Package(url: "https://github.com/adamnemecek/Phantomlike.git", majorVersion: 1)
    ]
)

Usage

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

However

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

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