Warm tip: This article is reproduced from stackoverflow.com, please click
cocoa-touch foundation ios nsdata swift

Print the size (megabytes) of Data in Swift

发布于 2020-04-19 09:30:37

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?

Questioner
user2512523
Viewed
19
Mozahler 2017-03-11 12:35

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