Home > Net >  Measurement API in Swift (Ignore Locale) When Formatting Output
Measurement API in Swift (Ignore Locale) When Formatting Output

Time:01-26

I have a convert function which returns the Measurement to the user. This allows me to covert between different units. The problem is when I print the value using the formatted function, it always shows as ft, since my locale is set that way. How can I make sure that it shows the correct formatting for units like m for meters or cm for centimeters etc.

extension Double {
    
    func convert(from: UnitLength, to: UnitLength) -> Measurement<UnitLength> {
        let measurement = Measurement(value: self, unit: from)
        return measurement.converted(to: to)
    }
    
}

struct ContentView: View {
    
    let distance: Double = 100    
   
    var body: some View {
        VStack {
            // formatted always prints out the result as locale aware
            // how can I make it print centimeters or meters etc
            Text(distance.convert(from: UnitLength.meters, to: UnitLength.centimeters).formatted())
        }
    }
}

CodePudding user response:

If you use the .formatted property of your measurement then you get

a locale-aware string representation of a measurement

You will need to create your own MeasurementFormatter and specify the .providedUnit option

This will ignore your locale and format the measurement using the unit of the measurement (in this case cm)

struct ContentView: View {
    
    let distance: Double = 100 

    let formatter: MeasurementFormatter = {
        let formatter = MeasurementFormatter()
        formatter.unitOptions = .providedUnit
        return formatter
    }()   
   
    var body: some View {
        VStack {
            // formatted always prints out the result as locale aware
            // how can I make it print centimeters or meters etc
            Text(self.formatter.string(from:distance.convert(from: UnitLength.meters, to: UnitLength.centimeters)))
        }
    }
}
  •  Tags:  
  • Related