Print the size (megabytes) of Data in Swift

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

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


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)