Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 758
Arsen Avatar asked Oct 17 '22 22:10

Arsen


2 Answers

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
like image 161
Arsen Avatar answered Oct 21 '22 06:10

Arsen


The description method of HKQuantity does not return a localized value and it is meant for debugging, not for display. Convert the HKQuantity instance to an NSMeasurement and use NSMeasurementFormatter (documentation here) to localize the value for display.

like image 38
Allan Avatar answered Oct 21 '22 07:10

Allan