How to dysplay byte counts in Swift


Greetings, traveler!

There are several ways to display formatted string representations of byte counts in Swift. We will figure out how to do it with both ByteCountFormatter and ByteCountFormatStyle. Let’s check some examples using SwiftUI.

ByteCountFormatter

ByteCountFormatter in Swift can format byte counts into human-readable strings like “10 MB” or “1.24 GB”. Using ByteCountFormatter in SwiftUI is pretty straightforward. Here’s how you can do it:

struct ContentView: View {
    
    @State private var byteCount: Int64 = 1024
    
    var body: some View {
        Text(ByteCountFormatter.string(fromByteCount: byteCount, countStyle: .file))
    }
    
}

If you want to make sure the formatter only uses specific units, you can do something like this:

struct ContentView: View {
    
    @State private var byteCount: Int64 = 1024
    
    private let formatter: ByteCountFormatter = {
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = [.useKB, .useMB, .useGB]
        return formatter
    }()
        
    var body: some View {
        Text(formatter.string(fromByteCount: byteCount))
    }
    
}

ByteCountFormatStyle

You can also display byte counts with the ByteCountFormatStyle struct. Let’s figure out how to do it:

struct ContentView: View {
    
    @State private var byteCount: Int64 = 1024
        
    var body: some View {
        // "1 kB"
        Text(byteCount.formatted(.byteCount(style: .file)))
    }
    
}

You can customize this style as well.

struct ContentView: View {
    
    @State private var byteCount: Int64 = 1024
    
    private let style = ByteCountFormatStyle(
        style: .memory,
        allowedUnits: [.kb],
        spellsOutZero: true,
        includesActualByteCount: false,
        locale: Locale(identifier: "en_US")
    )
        
    var body: some View {
        // "1 kB"
        Text(style.format(byteCount))
    }
    
}