88

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?

2
  • Swift 5.1 answer Commented Feb 4, 2020 at 21:47
  • This works unaltered without any warnings or errors on Swift 5.4.2. What's special about 5.1? Commented Aug 25, 2021 at 15:05

11 Answers 11

158

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
Sign up to request clarification or add additional context in comments.

3 Comments

This is also userful for pdf and ppt files.
I tried this but I am getting output like: There were 1675125 bytes ||||| formatted result: 1,7 MB.....why comma here?
It might have to do with your localized settings.
37

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)

9 Comments

Since the OP seems confused about how to get the count property out of a Data instance, maybe you should update your answer to use that instead of a hardcoded number.
Oops - just noticed the comment in your code. That's not too obvious.
@rmaddy If I'm going to invest the time to OP's question, I don't think it's unreasonable to expect that they actually read the entirety of the answer :p
Voted up. I forgot about the byte count formatter, even though I use it all the time... Nice touch.
@rmaddy I just checked, and there's no NSDimmension for information storage (bytes). Am I missing something?
|
20

Swift 5.1

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

Usage:

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

Comments

19

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

4 Comments

count represents bits or bytes?
Count represents bytes of data.
@abdullahselek I can not find description in apple's document. Do you?
@songgeb I didn't check but you can count in Foundation.
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))
 }}

Comments

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

1 Comment

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

1 Comment

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'"
1
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.

1 Comment

It should be let megabytes = bytes / (8 * 1024 * 1024)
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.

Comments

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

Comments

-1

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

1 Comment

There's a type error: pow is (Double, Double) -> Double, but count is Int. You can't multiple Double by Int.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.