Nick Kohrn
Nick Kohrn

Reputation: 6049

Use Foundation's Measurement API to Perform Custom Unit Conversion

I have three units of measurement that I need to convert between, and two of them are not provided by Foundation. One of the units, which is provided by Foundation is UnitDispersion.partsPerMillion. The other two units are .millequivalentsPerLiter and degreesOfCarbonateHardness.

The math that I need to use follows:

1 meq/L = 2.8 dKH = 50 ppm

I have tried to subclass Foundation.UnitConverter, but I don't understand how to use baseUnitValue(fromValue value: Double) -> Double and value(fromBaseUnitValue baseUnitValue: Double) -> Double to create the correct results.

Do I need to subclass Foundation.UnitConverter or Foundation.UnitConverterLinear? Do I need to create a subclass of UnitConverter for the conversion between each unit?

Upvotes: 3

Views: 173

Answers (1)

Rob Napier
Rob Napier

Reputation: 299425

As a rule, you don't subclass UnitConverter. Instead you make concrete instances of UnitConverterLinear. For example:

extension UnitDispersion {
    static let millequivalentsPerLiter =
        UnitDispersion(symbol: "meq/L",
                       converter: UnitConverterLinear(coefficient: 50))
}

let value = Measurement(value: 1, 
                        unit: UnitDispersion.millequivalentsPerLiter) // 1.0 meq/L
value.converted(to: .partsPerMillion) // 50.0 ppm

Upvotes: 2

Related Questions