Search code examples
swifthealthkit

How to convert between volumetric HKUnits?


I'm currently working on adding localisation support for volumetric units in my app. For example I want to be able to change from fluid ounces to litres and back again. Basically I want to support all the volumetric units that HKUnit supports with .dietaryWater.

Apple does say that "You can request the value from a quantity object in any compatible units.", but are very unclear how one would do this. (link)

How can I do conversations between units without writing the math myself?


Solution

  • According to the link you provided, under Working With Units:

    var value = HKQuantity(unit: .fluidOunceUS(), doubleValue: 42)
    var convertedValue = value.doubleValue(for: .liter())
    

    https://developer.apple.com/documentation/healthkit/hkquantity/1615245-doublevalue