在Swift 3中设置中等和长期测量符号 [英] Setting medium and long measurement symbols in Swift 3

查看:90
本文介绍了在Swift 3中设置中等和长期测量符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,当我创建自定义单位时,我只能定义一个符号.使用内置单元可以有短,中和长单元.如何为自定义单位设置其他单位样式?

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))

输出:

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

推荐答案

简短答案-您不能.该API没有提供任何功能,可让您为这三种单位样式提供不同的符号.

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

对于自定义单位,MeasurementFormatter仅在定义自定义单位时使用一个符号.

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.

然后是将单元本地化的问题. Foundation框架为所有受支持的语言提供了所有这些信息,因此MeasurementFormatter可以显示所有预定义单位的所有受支持语言的所有三种单位样式.

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.

由于API确实支持自定义单位,但不提供特定于单位样式的符号的功能,所以我建议向Apple提出增强请求.

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.

这篇关于在Swift 3中设置中等和长期测量符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆