Setting medium and long measurement symbols in Swi

2019-03-01 12:00发布

In Swift when I create custom units I can only define one symbol. With the built in units there can be short, medium and long units. How do you set the other unit styles for a custom unit?

extension UnitEnergy {
    static let footPounds = UnitEnergy(symbol: "ft-lbs", converter: UnitConverterLinear(coefficient: 1))
}

var test = Measurement<UnitEnergy>( value: 10, unit: .footPounds)
var formatter = MeasurementFormatter()

formatter.locale = Locale(identifier: "es")

formatter.unitStyle = .short
print( formatter.string(from: test))

formatter.unitStyle = .medium
print( formatter.string(from: test))

formatter.unitStyle = .long
print( formatter.string(from: test))

formatter.unitOptions = .providedUnit

formatter.unitStyle = .short
print( formatter.string(from: test))

formatter.unitStyle = .medium
print( formatter.string(from: test))

formatter.unitStyle = .long
print( formatter.string(from: test))

Output:

10 J
10 J
10 julios
10 ft-lbs
10 ft-lbs
10 ft-lbs

1条回答
我想做一个坏孩纸
2楼-- · 2019-03-01 12:46

Short answer - you can't. The API does not provide any facility that allows you to provide different symbols for the three unit styles.

For custom units, the MeasurementFormatter only has the one symbol used when defining the custom unit.

Keep in mind that the need is for much more than just three different possible symbols for the three different unit styles. You would actually need three different string formats because some units might have a space or other punctuation, some might not. Some might appear before the value while some appear after the value.

And then there is the issue of localizing the unit. The Foundation framework provides all of this information for all supported languages so MeasurementFormatter can show all three unit styles for all supported languages for all predefined units.

Since the API does support custom units but not the ability to provide unit style specific symbols, I would suggest filing an enhancement request with Apple.

查看更多
登录 后发表回答