2016-11-28 64 views
1

当我在Playground中运行以下代码时,格式化的字符串返回为零。我在派生的自定义Measurement类中缺少什么?在派生单元中使用MeasurementFormatter

open class UnitFlowRate : Dimension { 
    open override static func baseUnit() -> UnitFlowRate { return self.metricTonsPerHour } 

    static let shortTonsPerHour = UnitFlowRate(symbol: NSLocalizedString("stph", comment: "short tons per hour"), converter: UnitConverterLinear(coefficient: 1)) 
    static let metricTonsPerHour = UnitFlowRate(symbol: NSLocalizedString("mtph", comment: "metric tons per hour"), converter: UnitConverterLinear(coefficient: 2)) 
} 

var measureCustom = Measurement<UnitFlowRate>(value: 12.31, unit: .shortTonsPerHour) 
var measureSystem = Measurement<UnitLength>(value: 12.31, unit: .inches) 

var formatter = MeasurementFormatter() 
var measureStringCustom = formatter.string(for: measureCustom) 
var measureStringSystem = formatter.string(for: measureSystem) 
print(measureCustom) // This works 
print(measureSystem) // This works 
print(measureStringCustom) // This is nil - Why? 
print(measureStringSystem) // This works 

输出:

12.31 stph 
12.31 in 
nil 
Optional("0 mi") 

回答

1

你需要在你的代码更新了一些东西。

首先,使用的是在Formatter这需要Any?并返回一个可选Stringstring方法。如果更改参数名称from,你会用它返回一个非可选上MeasurementFormatter定义的方法:

var measureStringCustom = formatter.string(from: measureCustom) 

其次,您使用的是MeasurementFormatter它具有unitOptions属性设置为.naturalScale(默认) 。如果将其更改为.providedUnit,则会看到您现在获得了一些输出。问题是.naturalScale将对给定的语言环境使用适当的单位,目前没有办法设置自定义Dimension子类的内容。

所以,这种实现方式你什么是使用converted方法与.providedUnit格式化一起,像这样的内容:

let converted = measureCustom.converted(to: .metricTonsPerHour) 
var formatter = MeasurementFormatter() 
formatter.unitOptions = .providedUnit 
print(formatter.string(from: converted)) 

最后,你可能仍然没有得到你所期望的输出。这是因为由baseUnit返回的UnitConverterLinearcoefficient应该是1。我希望你打算按如下方式定义你的尺寸(注意缩小系数):

open class UnitFlowRate : Dimension { 
    open override static func baseUnit() -> UnitFlowRate { return self.metricTonsPerHour } 
    static let shortTonsPerHour = UnitFlowRate(symbol: NSLocalizedString("stph", comment: "short tons per hour"), converter: UnitConverterLinear(coefficient: 0.5)) 
    static let metricTonsPerHour = UnitFlowRate(symbol: NSLocalizedString("mtph", comment: "metric tons per hour"), converter: UnitConverterLinear(coefficient: 1)) 
}