// SI units
enum Magnitude : Measurement {
case Milli = Measurement(-3, \"ml\")
case Centi = Measurement(-2, \"cl\")
case Desi = Measurement(-1, \"dl\")
Depending on what you need, maybe you can combine an enumeration of SI unit scales and the example in the Computed Properties section of Apple Swift Programming Guide. In this simplistic scheme all of input measurements would be stored in the same units (grams in this example). Then you would convert to whatever units you needed in the output.
It is very readable.
enum SI {
case kg
case hg
case dag
case g
case dg
case cg
case mg
var scale: Double {
switch self {
case kg: return 0.001
case hg: return 0.01
case dag: return 0.1
case g: return 1.0
case dg: return 10.0
case cg: return 100.0
case mg: return 1000.0
}
}
}
extension Double {
var kg: Double {return self * 1000.0}
var hg: Double {return self * 100.0}
var dag: Double {return self * 10.0}
var g: Double {return self}
var dg: Double {return self * 0.1}
var cg: Double {return self * 0.01}
var mg: Double {return self * 0.001}
func convertTo(si: SI) -> Double {return self * si.scale}
}
Example:
