Created
October 23, 2014 01:57
-
-
Save tjw/36ad5e1978e503c06bd4 to your computer and use it in GitHub Desktop.
Geometric types with units
This file contains 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
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