目录
目录README.md

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.

关于
63.0 KB
邀请码
    Gitlink(确实开源)
  • 加入我们
  • 官网邮箱:gitlink@ccf.org.cn
  • QQ群
  • QQ群
  • 公众号
  • 公众号

©Copyright 2023 CCF 开源发展委员会
Powered by Trustie& IntelliDE 京ICP备13000930号