apple / swift-foundation

The Foundation project
Apache License 2.0
2.35k stars 149 forks source link

Custom Dimension: how to support internationalisation in the symbols and UnitLength? #503

Open alpennec opened 5 months ago

alpennec commented 5 months ago

I've defined a custom Dimension to represent the pace.

public final class UnitPace: Dimension {
    public static let secondsPerMeter = UnitPace(
        symbol: "s/m",
        converter: UnitConverterLinear(coefficient: 1)
    )
}

extension Measurement where UnitType == UnitPace {
     public init(
        minutes: Int,
        seconds: Int,
        unit: UnitPace
    ) {
        let value = Double(minutes) + Double(seconds) / 60

        self.init(
            value: value,
            unit: unit
        )
    }
}

I want to format a Measurement<UnitPace> so it can be shown in the UI.

let paceMeasurement: Measurement<UnitPace> = Measurement<UnitPace>(
     minutes: 5, 
     seconds: 30, 
     unit: .secondsPerMeter
)

Text(paceMeasurement.formatted(.measurement(width: .narrow, numberFormatStyle: .number.precision(.fractionLength(0...1)))) ?? "-")

// "... s/m" is displayed

How can I specify the localised strings for the different UnitStyle (short, medium, long) / UnitWidth (wide, abbreviated, narrow) to use?

itingliu commented 5 months ago

It's currently impossible to extend localization support to custom Dimension, unfortunately. Currently we rely exclusively on ICU to fetch the localization. I imagine we'd need to add a hook in Measurement.FormatStyle to take localization via, say, our string localization infrastructure. Such "hook" will probably be public to allow extension in your own type, which means new API as well.