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

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)

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


Swift 5.1

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

Usage:

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

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))
 }}