我正在构建一个将cm转换为英尺-英寸的格式化程序。
这是我的代码:
struct LengthFormatters {
static let imperialHeight: LengthFormatter = {
let formatter = LengthFormatter()
formatter.numberFormatter.roundingMode = NumberFormatter.RoundingMode.halfUp
formatter.numberFormatter.maximumFractionDigits = 0
formatter.isForPersonHeightUse = true
formatter.unitStyle = .short
return formatter
}()
}
extension Measurement where UnitType : UnitLength {
var heightOnFeetsAndInches: String? {
guard let measurement = self as? Measurement<UnitLength> else {
return nil
}
let meters = measurement.converted(to: .meters).value
return LengthFormatters.imperialHeight.string(fromMeters: meters)
}
}