Tom Harrington Tom Harrington - 2 months ago 24
iOS Question

Choosing units with MeasurementFormatter

This is similar to a question I asked yesterday but the answer I got doesn't seem to work in this case.

I'm getting altitude values in meters from Core Location. I want to display these in a localized form. As an example, the altitude where I am right now is 1839m above sea level. This should be displayed as 6033 feet. The best I can do with

MeasurementFormatter
is "1.143 mi".

let meters : Double = 1839
let metersMeasurement = Measurement(value: meters, unit: UnitLength.meters)

let measurementFormatter = MeasurementFormatter()
measurementFormatter.locale = Locale(identifier: "en_US")

let localizedString = measurementFormatter.string(from: metersMeasurement)


The
.naturalScale
option that answered my previous question doesn't help here. I think this is a limitation of the framework, but I wonder if anyone has a workaround for now.

Answer

Just create a Double extension to convert your meters unit to feet. Then just use MeasurementFormatter to display it as needed:

extension Double {
    var metersToFeet: Double {
        return Measurement(value: self, unit: UnitLength.meters).converted(to: UnitLength.feet).value
    }
}

Playground

let measurementFormatter = MeasurementFormatter()
measurementFormatter.locale = Locale(identifier: "en_US")
measurementFormatter.unitOptions = .providedUnit
measurementFormatter.numberFormatter.maximumFractionDigits = 0
measurementFormatter.unitStyle = .long

let meters: Double = 1839
let localizedString = measurementFormatter.string(from: Measurement(value: meters.metersToFeet, unit: UnitLength.feet))

localizedString //   // "6,033 feet"