Print the size (megabytes) of Data in Swift

user2512523 picture user2512523 · Mar 10, 2017 · Viewed 37.7k times · Source

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?

Answer

Mozahler picture Mozahler · Mar 10, 2017

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

    func stackOverflowAnswer() {
      if let data = UIImagePNGRepresentation(#imageLiteral(resourceName: "VanGogh.jpg")) as Data? {
      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