2016-11-28 62 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)) 
}