Search code examples
iosswifthealthkit

Format speed in Swift


I want to be able to format and print speed in localised form. I found a few pods that can do that but I'm looking for embedded solution (if possible).

Currently I do next:

 let unit = HKUnit.meterUnit(with: .kilo).unitDivided(by: .hour())
 let output = HKQuantity(unit: unit, doubleValue: 12.5).description

But in this case I cannot tune anything like use h instead of hr.


Solution

  • As said @Allan we have to use MeasurementFormatter. Check out the ready to use solution below.

    import UIKit
    import HealthKit
    
    let value = NSMeasurement(doubleValue: 12.5, unit: UnitSpeed.milesPerHour)
    let formatter = MeasurementFormatter()
    formatter.numberFormatter.maximumFractionDigits = 2
    formatter.string(from: value as Measurement<Unit>) // prints 12.5 mph