HKUnit and HKQuantity should be moved to Foundation

Originator:brent
Number:rdar://17409575 Date Originated:21-Jun-2014 07:22 PM
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode6-Beta2 (6A216f)
Classification:Feature (New) Reproducible:Always
 
Summary:
The HKUnit and HKQuantity classes in HealthKit have the potential to be extremely useful in non-health-related applications. They should be moved to Foundation and enhanced to allow use in a wider variety of applications. The new NSUnit should be extended to allow additional units and types of units to be added by developers, and NSQuantity should allow 64-bit integer and NSDecimal representations in addition to doubles.

Steps to Reproduce:
1. Open a Playground and input something like:

    import Foundation
    
    let inches = NSUnit.inchesUnit()
    let centimeters = NSUnit.meterUnitWithMetricPrefix(.Centi)
    
    let rulerLength = NSQuantity(unit:inches doubleValue:12.0)
    println("\(rulerLength.doubleValueForUnit(centimeters)) cm")

Expected Results:
The output “30.48 cm”.

Actual Results:
A variety of compiler errors.

Notes:
Reasoning about units is a common thing for apps to do. Even leaving aside app-specific concerns, we see this within the frameworks themselves:

* Core Location uses meters to measure distance, but many users want them displayed in Imperial units.
* Core Location and NSBezierPath use degrees to measure angles, but UIBezierPath and CGPath use radians.
* Most time-related APIs use NSTimeInterval’s floating-point seconds representation, but some use microseconds or nanoseconds.
* Data size APIs use integer numbers of bytes—sometimes extremely large numbers.

The frameworks use a variety of approaches to handle these mismatches. MKDistanceFormatter and NSByteCountFormatter handle conversions internally, but other formatters do not. For time, you must usually multiply or divide by an appropriate constant. For degrees and radians, you must memorize a small formula to use at appropriate points.

HealthKit contains the beginnings of a solution: a pair of classes that allow the programmer to work with units in a simple way, without having to memorize anything or use a formatter intended for end users. At first glance, they even seem to support dimensional analysis, which has the potential to expose unit errors when programming. I think these classes should be hoisted out of HealthKit and into Foundation, where they can benefit all sorts of code, not just health apps.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!