Bytes Count Formatting

Value in bytes can be converted into localized human-readable form by using ByteCountFormatter:

ByteCountFormatter.string(fromByteCount: 12345678, countStyle: .file) // '12.3 MB'

If more options need to be configured, instantiate ByteCountFormatter:

let formatter = ByteCountFormatter()
formatter.allowedUnits = .useAll
formatter.countStyle = .file
formatter.includesUnit = true
formatter.isAdaptive = true

formatter.string(fromByteCount: 123456789000) // '123.46 GB'
formatter.string(fromByteCount: 0) // 'Zero KB'

The formatter will automatically pick the most suitable measurement unit, since we specified useAll option. It can be forced to use one or more pre-defined units.

By setting isAdaptive to true, we instructed the formatter to automatically pick the number of fraction digits based on the magnitude, e.g. 1 digit for megabytes, 2 for gigabytes and above.

Further reading

Thanks for reading!

If you enjoyed this post, be sure to follow me on Twitter to keep up with the new content. There I write daily on iOS development, programming, and Swift.

Vadim Bulavin

Creator of Yet Another Swift Blog. Senior iOS Engineer at Pluto TV. Coding for fun since 2008, for food since 2012.