Skip to content

Instantly share code, notes, and snippets.

@tjw
Created October 23, 2014 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjw/36ad5e1978e503c06bd4 to your computer and use it in GitHub Desktop.
Save tjw/36ad5e1978e503c06bd4 to your computer and use it in GitHub Desktop.
Geometric types with units
public protocol MeasurementUnit {
// If we have one of this unit, how many millimeters is it?
class var asMillimeters: Double { get }
}
public class Millimeter : MeasurementUnit {
public class var asMillimeters: Double {
get {
return 1.0
}
}
}
public class Inch : MeasurementUnit {
public class var asMillimeters: Double {
get {
return 25.4
}
}
}
public struct Point<T:MeasurementUnit> {
let x: Double = 0.0;
let y: Double = 0.0;
func convert<U:MeasurementUnit>() -> Point<U> {
let scale = U.asMillimeters / T.asMillimeters
let xc = x * scale
let yc = y * scale
return Point<U>(x:xc, y:yc)
}
}
public func toIn<T:MeasurementUnit>(p:Point<T>) -> Point<Inch> {
return p.convert()
}
let r_mm = Point<Millimeter>(x:1.0, y:2.0)
let r_in = toIn(r_mm)
println("r_in:\(r_in.x), \(r_in.y)\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment