Extend Measurement to support inverse units

There are many units which are inverse of standard units, e.g. wave period vs Hz, pace vs speed, Siemens vs Ohms, ...

Dimension can be subclassed to create the custom units.

How to extend Measurement.converted( to: )?
I was looking at somehow using UnitConverter and subclass to something like UnitConverterInverse.

Thoughts?

Dimension can be subclassed to create the custom units.

You probably don't want to subclass Dimension for reciprocal units since there's no good way to convert between measurements of different Dimension types. Instead, you can extend the existing classes to add the new reciprocal units, and then conversion will work like usual.

subclass [UnitConverter] to something like UnitConverterInverse

Yep you'll need that.

Interestingly, there's already a reciprocal unit buried in the existing measurement API. It uses a reciprocal converter that is exactly what you need, but unfortunately isn't part of the public API. Check this out:

Welcome to Apple Swift version 6.2.3 (swiftlang-6.2.3.3.21 clang-1700.6.3.2).
Type :help for assistance.
  1> import Foundation
  2> print(UnitFuelEfficiency.litersPer100Kilometers.converter) 
<_NSStatic_NSStaticUnitConverterLinear_NoConst: 0x20761bfc8> coefficient = 1.000000, constant = 0.000000
  3> print(UnitFuelEfficiency.milesPerGallon.converter) 
<NSUnitConverterReciprocal: 0x10055d880> reciprocalValue = 235.215000
  4> print(UnitFuelEfficiency.milesPerImperialGallon.converter) 
<NSUnitConverterReciprocal: 0x10055f400> reciprocalValue = 282.481000

So the system already has this internal NSUnitConverterReciprocal just to support the fuel efficiency dimension. That bit of debug output basically shows exactly how it works. It’s actually simpler than the linear converter since it has a coefficient (reciprocalValue) but no constant.

For now I'd propose you do this:

  • make your own version of this reciprocal converter;
  • extend the relevant existing dimension classes with your new units (for your examples above this would be UnitFrequency, UnitSpeed, and UnitElectricResistance);
  • submit a Feedback requesting that UnitConverterReciprocal get promoted to the public API.
Extend Measurement to support inverse units
 
 
Q