Last active
November 10, 2021 04:12
-
-
Save wildthink/4b63ab16250f17d04b85309b5338b479 to your computer and use it in GitHub Desktop.
Syntactic Sugar for Measurements in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public typealias Mass = Measurement<UnitMass> | |
public typealias Duration = Measurement<UnitDuration> | |
public typealias Angle = Measurement<UnitAngle> | |
public typealias Length = Measurement<UnitLength> | |
public typealias Speed = Measurement<UnitSpeed> | |
public extension Measurement where UnitType: Dimension { | |
static var zero: Measurement<UnitType> { | |
Measurement(value: 0, unit: UnitType.baseUnit()) | |
} | |
} | |
public extension Double { | |
func callAsFunction <U: Dimension>(_ units: U) -> Measurement<U> { | |
Measurement(value: self, unit: units) | |
} | |
} | |
public extension Int { | |
func callAsFunction <U: Dimension>(_ units: U) -> Measurement<U> { | |
Measurement(value: Double(self), unit: units) | |
} | |
} | |
public extension UnitDuration { | |
static let SecondsPerDay: Double = 86_400 | |
static let days = UnitDuration("days", coefficient: SecondsPerDay) | |
static let weeks = UnitDuration("weeks", coefficient: SecondsPerDay * 7) | |
static let months = UnitDuration("months", coefficient: SecondsPerDay * 30.417) | |
static let years = UnitDuration("years", coefficient: SecondsPerDay * 365) | |
convenience init (_ symbol: String, coefficient: Double) { | |
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient)) | |
} | |
} | |
public extension Measurement { | |
init (_ value: Double, _ unit: UnitType) { | |
self.init(value: value, unit: unit) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment