测量格式化程序:space 介于值和单位之间

Measurement Formatter: space between value and unit

我有一个 Measurement 属性:

let measurement = Measurement(value: 10000.0, unit: UnitMass.grams)

我想打印成字符串。我使用以下 MeasurementFormatter:

let measurementFormatter = MeasurementFormatter()
measurementFormatter.unitStyle = .short
measurementFormatter.numberFormatter.numberStyle = .decimal

print(measurementFormatter.string(from: measurement))

打印 10,000g.

如何打印 10,000 g,即在值和单位之间添加 space?

问题是您使用的样式 .short。只需注释掉这一行,它就会在它们之间显示一个 space:

let measurement = Measurement(value: 10000, unit: UnitMass.grams)
let measurementFormatter = MeasurementFormatter()
// measurementFormatter.unitStyle = .short
measurementFormatter.unitOptions = .providedUnit
measurementFormatter.numberFormatter.numberStyle = .decimal
print(measurementFormatter.string(from: measurement))    // "10,000 g\n"