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 bytesformatted result: 28.9 MB
If your goal is to print the size to the use, use ByteCountFormatter
import Foundationlet byteCount = 512_000 // replace with data.countlet bcf = ByteCountFormatter()bcf.allowedUnits = [.useMB] // optional: restricts the units to MB onlybcf.countStyle = .filelet string = bcf.string(fromByteCount: Int64(byteCount))print(string)
You can use count
of Data object and still you can use length
for NSData