简体   繁体   中英

Best way to extend Measurement Unit with non existing type?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM