Add more conversion units to existing apple classes of conversion

112 views Asked by At

Is it possible to add more conversion units to existing apple classes of conversion ?

https://developer.apple.com/documentation/foundation/unittemperature On above link Rankine is not available. How to customize/extend this class and add Rankine ?

PS. Rankine sample formula is : 5°C × 9/5 + 491.67 = 500.67°R

PPS. planning to use it this way

let celsius = Measurement(value: 4, unit: UnitTemperature.celsius)
let kelvins = celsius.converted(to: UnitTemperature.kelvin)
print(kelvins)

TIA

1

There are 1 answers

2
Alexander On BEST ANSWER

Just follow the documentation in Dimension, which is the superclass of UnitTemperature.

UnitTemperature's base unit is Kelvin. So I just had to look up the formula for converting Rankine to Kelvin, which is just a linear coefficient (degreesKelvin = degressRakine * 5/9), and plug that in:

extension UnitTemperature {
    static var rankine = UnitTemperature(
        symbol: "°R",
        converter: UnitConverterLinear(coefficient: 5/9)
    )
}

let celsius = Measurement(value: 5, unit: UnitTemperature.celsius)
let rankin = celsius.converted(to: .rankine)
print(rankin) // => 500.66999999999996 °R