Print the size (megabytes) of Data in Swift

48,413

Solution 1

Use yourData.count and divide by 1024 * 1024. Using Alexanders excellent suggestion:

    func stackOverflowAnswer() {
      if let data = #imageLiteral(resourceName: "VanGogh.jpg").pngData() {
      print("There were \(data.count) bytes")
      let bcf = ByteCountFormatter()
      bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
      bcf.countStyle = .file
      let string = bcf.string(fromByteCount: Int64(data.count))
      print("formatted result: \(string)")
      }
    }

With the following results:

There were 28865563 bytes
formatted result: 28.9 MB

Solution 2

If your goal is to print the size to the use, use ByteCountFormatter

import Foundation

let byteCount = 512_000 // replace with data.count
let bcf = ByteCountFormatter()
bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
bcf.countStyle = .file
let string = bcf.string(fromByteCount: Int64(byteCount))
print(string)

Solution 3

You can use count of Data object and still you can use length for NSData

Solution 4

Swift 5.1

extension Int {
    var byteSize: String {
        return ByteCountFormatter().string(fromByteCount: Int64(self))
    }
}

Usage:

let yourData = Data()
print(yourData.count.byteSize)

Solution 5

Following accepted answer I've created simple extension:

extension Data {
func sizeString(units: ByteCountFormatter.Units = [.useAll], countStyle: ByteCountFormatter.CountStyle = .file) -> String {
    let bcf = ByteCountFormatter()
    bcf.allowedUnits = units
    bcf.countStyle = .file

    return bcf.string(fromByteCount: Int64(count))
 }}
Share:
48,413
user2512523
Author by

user2512523

Updated on July 08, 2022

Comments

  • user2512523
    user2512523 almost 2 years

    I have a variable fileData of Data type and I am struggling to find how to print the size of this.

    In the past NSData you would print the length but unable to do that with this type.

    How to print the size of a Data in Swift?