如何在 Swift 中获取本地化的文件大小单位

How to get localized file size units in Swift

我尝试了以下代码:

    let units: [ByteCountFormatter.Units] = [.useBytes, .useKB, .useMB, .useGB, .useTB, .usePB, .useEB, .useZB, .useYBOrHigher]

    let localizedDescriptions = units.map { (unit) -> String in
        let formatter = ByteCountFormatter()
        formatter.includesCount = false
        formatter.includesUnit = true
        formatter.allowedUnits = [unit]
        formatter.countStyle = .file
        return formatter.string(fromByteCount: .max)
    }

并期望根据 the documentation.

本地化

Class

ByteCountFormatter

A formatter that converts a byte count value into a localized description that is formatted with the appropriate byte modifier (KB, MB, GB and so on).

但不幸的是,我只有:

["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]

我测试了:

PS

无论如何感谢您阅读本文...

您不能将 locale 设置为 ByteCountFormatter,但可以使用 MeasurementFormatter

这是一个示例(根据需要修改 unitStyle 和其他属性)。

let units: [UnitInformationStorage] = [.bytes, .kilobytes, .megabytes, .gigabytes, .terabytes, .petabytes, .zettabytes, .yottabytes]

let localizedDescriptions = units.map({ unit -> String in

    let formatter = MeasurementFormatter()
    formatter.unitStyle = .short
    formatter.locale = Locale(identifier: "ru_RU") //hard coded here, I guess it takes the current one
    return formatter.string(from: unit)
})

输出:

$> ["Б", "кБ", "МБ", "ГБ", "ТБ", "ПБ", "ZB", "YB"]

Zetta 和 Yotta 没有翻译吗?

来自 NSHipster:

ByteCountFormatter, EnergyFormatter, MassFormatter, LengthFormatter, and MKDistanceFormatter are superseded by MeasurementFormatter.
Legacy Measure: ByteCountFormatter
Measurement Formatter Unit: UnitInformationStorage