[Measurement APIs] How to create custom Units and Dimensions (Part 2)

Francesco Leoni
2 min readJan 29, 2022

In this article we are going to lear how to create custom units and dimensions to extend the ones that Swift offers.

1. Creating a Custom Unit

To create a custom unit we need to use the initializer of the dimension we want to add a new unit to.

So if we want to add a new unit to UnitIlluminance, we can do the following:

let footCandleUnit = UnitIlluminance(symbol: “fc”, converter: UnitConverterLinear(coefficient: 10.76))

A coefficient of ‘10.76’ means that whenever a measurement of this unit is converted to the base unit, which is .lux, it will be multiplied by ‘10.76’.

Now we can convert .lux to .footCandle:

let footCandle = Measurement(value: 2, unit: footCandleUnit)
let lumen = footCandle.converted(to: .lux)

2. Extending an Existing Dimension

The second method uses an extension to add custom units.

extension UnitIlluminance { 
static let footCandle = UnitIlluminance(symbol: “fc”, converter: UnitConverterLinear(coefficient: 10.76))
}

We declare the new unit exactly as previously, passing a symbol and a coefficient. Now we can use this new unit in a slightly different way.

let footCandle = Measurement(value: 2, unit: UnitIlluminance.footCandle)
let lumen = footCandle.converted(to: .lux)

3. Creating a Custom Dimension

Swift allow us to create a whole new dimension by creating a subclass of Dimension.

Here is the example that Apple used in its documentation:

class CustomRadioactivityUnit: Dimension {    
static let becquerel = CustomRadioactivityUnit(symbol: "Bq", UnitConverterLinear(coefficient: 1.0))
static let curie = CustomRadioactivityUnit(symbol: "Ci", UnitConverterLinear(coefficient: 3.7e10))
static let baseUnit = self.becquerel
}
  1. First you create the units of the dimension, as we’ve seen previously.
  2. Then you define the base unit of the new dimension using the baseUnit property.

Conclusion

As we’ve seen, creating custom units and dimensions is an easy task, and most of the time the built in dimensions are just what we need.

Thanks for reading ❤️

--

--

Francesco Leoni

Hi! My name is Francesco. I am an iOS / macOS developer and Apple addicted. Creator of Anubi, Aware, Linkboard and BrainDump.