Nuzhdin Vladimir
Nuzhdin Vladimir

Reputation: 1822

How to get localized file size units in Swift

I tried the following code:

    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)
    }

And expect it to be localized according to 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).

But unfortunately, I got only:

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

I tested:

PS

In any case thanks for reading this...

Upvotes: 3

Views: 1973

Answers (1)

Larme
Larme

Reputation: 26006

You cannot set a locale to ByteCountFormatter, but you can with MeasurementFormatter.

Here is a sample (modify the unitStyle and other properties as you need).

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)
})

Output:

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

Zetta & Yotta aren't translated though?

From NSHipster:

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

Upvotes: 5

Related Questions