0

I'm making a health app, and thought it would be nice to create some custom HKUnit to represent some data by extending HKUnit, but HealthKit documentation says we shouldn't extend or subclass it, so I went to Measurements (Dimension) to try creating a custom Unit.

Basically, creating a custom unit generally means to use a basic unit type (unitduration, length, mass, energy, etc) and a coefficient (converter). But how about when there isn't a type compatible with this unit?

Example: I want to create a BMI unit (kg/m^2 or equivalent) and BMR (Kcal/day), etc. So maybe a MetabolicUnit class with class vars such as bmi, bmr, etc ... As for unit, hopefully using the dividedBy and multipliedBy to get translated units automatically.

Any advice, good practices or already solved code? Being a fairly new framework with a too common name, it's hard to find anything meaningful. Thanks

Einharch
  • 69
  • 1
  • 4
  • What's wrong with creating `let bmi = HKUnit.gramUnit(with: .kilo).unitDivided(by: HKUnit.meter()).unitDivided(by: HKUnit.meter())`? – Sulthan Jan 16 '17 at 18:56
  • Thanks, I tried that already, but it only gives me a local HKUnit, not like extending the system framework. I was thinking of extending the Measurement/Unit to also get a free translation (formatter) and factor for moving between kg/m2 and lb/in^2, etc ... But still a bit unsure on making a **custom Measurement/Unit** that isn't just mass, length, speed, energy, etc – Einharch Jan 19 '17 at 01:52

1 Answers1

2

You can create an instance of HKUnit that represents BMI without subclassing or extending HKUnit. Here are two examples of how:

let bmiUnit = HKUnit(from: "kg/m^2")

Or

let meter = HKUnit.meter()
let bmiUnit = HKUnit.gramUnit(with: .kilo).unitDivided(by: meter).unitDivided(by: meter)
Allan
  • 7,039
  • 1
  • 16
  • 26
  • Thanks, It's something I already tried (albeit a bit differently as I did **_unitMultiplied(by:)_** inside the division, but same result). I'm still trying to do it in the **Measurement/Unit** space for few reasons, mainly the free translation when I display back to the user without having to check if they're on metric or imperial system or a complete different language. – Einharch Jan 19 '17 at 01:56