 The personal blog of Stuart Breckenridge

The Measurement Type

The new Measurement type1 is a hugely helpful addition to the Foundation framework. It allows for conversion amongst many different measurements:

• Acceleration
• Angle
• Area
• Concentration Mass
• Dispersion
• Duration
• Electric Charge
• Electric Current
• Electric Potential Difference
• Electric Resistance
• Energy
• Frequency
• Fuel Efficiency
• Length
• Illuminance
• Mass
• Power
• Pressure
• Speed
• Temperature
• Volume

Usage is simple:

var mLs = Measurement(value: 125, unit: UnitVolume.milliliters) // 125 mL
var flOz = mLs.converted(to: UnitVolume.fluidOunces) // 4.2267 fl oz

Apple has provided excellent documentation on how to subclass the Dimension type, and on extending existing Dimension types. My quick experiment was to create a new UnitUKCurrency type:

class UnitUKCurrency: Dimension {
static let pence = UnitUKCurrency(symbol: "pence", converter: UnitConverterLinear(coefficient: 1.0))
static let pounds = UnitUKCurrency(symbol: "pounds", converter: UnitConverterLinear(coefficient: 100.00))

override static func baseUnit() -> UnitUKCurrency {
return self.pence
}
}

Which, in use, looks like this:

let pennies = Measurement(value: 1234.0, unit: UnitUKCurrency.pence) // 1234.0 pence
let poundage = pennies.converted(to: UnitUKCurrency.pounds) // 12.34 pounds

If only Measurement was around for v1.2 of Baby’s Milk!

1. The NSMeasurement class in Objective-C. ↩︎