Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Switch system locale and reload my mac(Saw different file size format in finder: "КБ", "МБ"... instead of "KB", "MB")
  • Playground/macOS template project.
  • Switched "Application language" in macOS template project.

PS

In any case thanks for reading this...

like image 884
Nuzhdin Vladimir Avatar asked Sep 03 '25 04:09

Nuzhdin Vladimir


1 Answers

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

like image 54
Larme Avatar answered Sep 05 '25 01:09

Larme