75

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?

Juan Boero
  • 6,281
  • 1
  • 44
  • 62
user2512523
  • 1,229
  • 2
  • 15
  • 25

11 Answers11

144

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
Mattia Righetti
  • 1,265
  • 1
  • 18
  • 31
Mozahler
  • 4,958
  • 6
  • 36
  • 56
36

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)
Alexander
  • 59,041
  • 12
  • 98
  • 151
17

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

abdullahselek
  • 7,893
  • 3
  • 50
  • 40
17

Swift 5.1

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

Usage:

let yourData = Data()
print(yourData.count.byteSize)
Juan Boero
  • 6,281
  • 1
  • 44
  • 62
6

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))
 }}
Jovan Stankovic
  • 4,661
  • 4
  • 27
  • 16
5

A quick extension for getting Data size in megabytes as Double.

extension Data {
    func getSizeInMB() -> Double {
        let bcf = ByteCountFormatter()
        bcf.allowedUnits = [.useMB]
        bcf.countStyle = .file
        let string = bcf.string(fromByteCount: Int64(self.count)).replacingOccurrences(of: ",", with: ".")
        if let double = Double(string.replacingOccurrences(of: " MB", with: "")) {
            return double
        }
        return 0.0
    }
}
Muhammed Gül
  • 825
  • 10
  • 19
  • 1
    Just a warning here, due to locale and language settings, the hardcoded comma and dot, and the MB letters could be missing/wrong. Maybe it's better to filter characters to only numbers or alike. – Juan Boero Aug 31 '21 at 15:34
4

Enter your file URL in the following code to get file size in MB, I hope this helps you.

let data = NSData(contentsOf: FILE URL)!
let fileSize = Double(data.count / 1048576) //Convert in to MB
print("File size in MB: ", fileSize)
Volodymyr Kulyk
  • 6,455
  • 3
  • 36
  • 63
AtulParmar
  • 4,358
  • 1
  • 24
  • 45
  • 1
    Don't suppose you have an update for Swift 4.2 do you? Currently, using this you can see "Instance member 'length' cannot be used on type 'Data'" – Jonas Jun 11 '19 at 08:58
0

If you want to just see number of bytes, printing the data object directly can give that to you.

let dataObject = Data()
print("Size is \(dataObject)")

Should give you:

Size is 0 bytes

In other words, .count won't be necessary in newer Swift 3.2 or higher.

Dino Alves
  • 113
  • 10
0

To get the size of a string, adapted from @mozahler's answer

if let data = "some string".data(using: .utf8)! {
  print("There were \(data.count) bytes")
  let bcf = ByteCountFormatter()
  bcf.allowedUnits = [.useKB] // optional: restricts the units to MB only
  bcf.countStyle = .file
  let string = bcf.string(fromByteCount: Int64(data.count))
  print("formatted result: \(string)")
}
spnkr
  • 952
  • 9
  • 18
0
func sizeInMB(data: Data) -> String {
    let bytes = Double(data.count)
    let megabytes = bytes / (1024 * 1024)
    return String(format: "%.2f MB", megabytes)
}

The following takes in a Data object as an argument and calculates the size of that Data in megabytes. The size is then returned as a String with a maximum of 2 decimal places.

Javier Cadiz
  • 12,326
  • 11
  • 55
  • 76
-1

count should suit your needs. You'll need to convert bytes to megabytes (Double(data.count) / pow(1024, 2))

atreat
  • 4,243
  • 1
  • 30
  • 34
  • There's a type error: pow is `(Double, Double) -> Double`, but `count` is `Int`. You can't multiple `Double` by `Int`. – Alexander Mar 10 '17 at 16:46