Created
October 23, 2014 02:38
-
-
Save tjw/431896be995e1f950e7f to your computer and use it in GitHub Desktop.
Unit types
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
import Foundation | |
@objc protocol MeasurementUnit { | |
// If we have one of this unit, how many millimeters is it? | |
class var asMillimeters: Double { get } | |
var value: Double { get } | |
init(_:Double) | |
} | |
class Millimeter : MeasurementUnit { | |
class var asMillimeters: Double { | |
get { | |
return 1.0 | |
} | |
} | |
let value: Double | |
required init(_ value:Double) { | |
self.value = value | |
} | |
} | |
class Inch : MeasurementUnit { | |
class var asMillimeters: Double { | |
get { | |
return 25.4 | |
} | |
} | |
let value: Double | |
required init(_ value:Double) { | |
self.value = value | |
} | |
} | |
func convert<T:MeasurementUnit, U:MeasurementUnit>(m: T) -> U { | |
let factor = U.asMillimeters / T.asMillimeters | |
return U(m.value * factor) | |
} | |
let in_measurement: MeasurementUnit = Inch(5) | |
let mm_measurement: Millimeter = convert(in_measurement) | |
// xcrun -sdk macosx swiftc unit-type.swift | |
// ... which then crashes. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment