Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Foundation's Measurement API to Perform Custom Unit Conversion

Tags:

swift

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?

like image 472
Nick Kohrn Avatar asked Dec 08 '25 10:12

Nick Kohrn


1 Answers

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
like image 77
Rob Napier Avatar answered Dec 09 '25 22:12

Rob Napier