Skip to content

Instantly share code, notes, and snippets.

@tjw
Created October 23, 2014 02:38
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/431896be995e1f950e7f to your computer and use it in GitHub Desktop.
Save tjw/431896be995e1f950e7f to your computer and use it in GitHub Desktop.
Unit types
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