Iiro Alhonen
Iiro Alhonen

Reputation: 430

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?

Upvotes: 0

Views: 203

Answers (2)

Quentin Hayot
Quentin Hayot

Reputation: 7876

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

Upvotes: 2

slushy
slushy

Reputation: 12375

Foundation includes a Measurement structure that allows for a wide variety of unit conversions. For example, to convert from fluid ounces to liters:

let fluidOz = 32.0
let liters = Measurement(value: fluidOz, unit: UnitVolume.fluidOunces).converted(to: .liters).value
print(liters) // 0.946352

let degrees = 45.0
let radians = Measurement(value: degrees, unit: UnitAngle.degrees).converted(to: .radians).value
print(radians) // 0.7853981633974483

In addition to UnitVolume, there is also UnitSpeed, UnitMass, and many more.

https://developer.apple.com/documentation/foundation/measurement

Upvotes: 1

Related Questions