Setting medium and long measurement symbols in Swift 3

心不动则不痛 提交于 2019-12-01 06:30:55

问题


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:


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.



来源:https://stackoverflow.com/questions/40557269/setting-medium-and-long-measurement-symbols-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!