当我在Playground中运行以下代码时,格式化的字符串将返回为nil。我在派生的自定义Measurement类中缺少什么?
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")
答案 0 :(得分:1)
您需要更新代码中的一些内容。
首先,您使用string
上的Formatter
方法,该方法需要Any?
并返回一个可选的String
。如果您将参数名称更改为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))
最后,您可能仍然无法获得预期的输出。这是因为coefficient
返回的UnitConverterLinear
的{{1}}应为baseUnit
。我希望你打算如下定义你的维度(注意缩小的系数):
1