Swift
Data Size
Megabytes
Programming
Code Example

Print the size megabytes of Data in Swift

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

To measure the size of a Swift Data value, start with count, which returns the number of bytes in the payload. Once you have the byte count, converting to megabytes or formatting for display is straightforward, but it is important to choose the right unit and avoid a few common API mistakes.

Use count for the Actual Payload Size

Data is a collection of bytes, so count is the correct source of truth.

swift
1import Foundation
2
3let payload = Data(repeating: 0, count: 5_242_880)
4let bytes = payload.count
5
6print("Bytes: \(bytes)")

That value is the number of bytes stored in the data buffer. If you want megabytes, convert the integer to Double before dividing so you keep the fractional part.

swift
1import Foundation
2
3let payload = Data(repeating: 0, count: 5_242_880)
4let megabytes = Double(payload.count) / 1_000_000.0
5let mebibytes = Double(payload.count) / 1024.0 / 1024.0
6
7print(String(format: "%.2f MB", megabytes))
8print(String(format: "%.2f MiB", mebibytes))

Understand MB Versus MiB

These two units are close but not identical:

  • 'MB means one million bytes'
  • 'MiB means 1024 * 1024 bytes'

If the value is shown in a product UI, use whatever convention the rest of the product already uses. If the value is part of an engineering diagnostic, binary units are often clearer. The key is to pick one convention and stay consistent.

Wrap the Conversion in an Extension

If you need this calculation in several places, a small extension keeps the code readable.

swift
1import Foundation
2
3extension Data {
4    var sizeInMB: Double {
5        Double(count) / 1_000_000.0
6    }
7
8    var sizeInMiB: Double {
9        Double(count) / 1024.0 / 1024.0
10    }
11}
12
13let payload = Data(repeating: 1, count: 2_621_440)
14print(String(format: "%.2f MB", payload.sizeInMB))
15print(String(format: "%.2f MiB", payload.sizeInMiB))

This is a simple way to keep byte-to-size math out of business logic.

Use ByteCountFormatter for User-Facing Output

Manual conversion is fine for logs and internal calculations. For user-visible strings, ByteCountFormatter is usually better because it handles units and localization for you.

swift
1import Foundation
2
3let payload = Data(repeating: 0, count: 5_242_880)
4let formatter = ByteCountFormatter()
5formatter.allowedUnits = [.useKB, .useMB]
6formatter.countStyle = .binary
7formatter.includesUnit = true
8formatter.isAdaptive = true
9
10let result = formatter.string(fromByteCount: Int64(payload.count))
11print(result)

This is a strong choice for file browsers, attachment pickers, download screens, and storage summaries.

Do Not Use MemoryLayout<Data>.size

A very common mistake is using MemoryLayout<Data>.size.

swift
import Foundation

print(MemoryLayout<Data>.size)

That prints the size of the Data value type itself, not the size of the bytes it holds. The result may be a small fixed number and tells you nothing useful about the payload.

When the goal is file size or buffer size, always use count.

Practical Example with File Data

Here is a real-world example that reads a file and prints the size.

swift
1import Foundation
2
3let url = URL(fileURLWithPath: "/tmp/example.bin")
4let data = try Data(contentsOf: url)
5
6print("Raw bytes: \(data.count)")
7print(String(format: "Binary size: %.2f MiB", Double(data.count) / 1024.0 / 1024.0))

This pattern is useful for upload validation, caching diagnostics, or file-import tooling.

Common Pitfalls

The most common mistake is measuring the wrapper type rather than the payload. MemoryLayout<Data>.size is not the answer to this problem.

Another mistake is performing integer division by accident. If you divide only Int values, the decimal fraction disappears, which can make the displayed size look lower than expected.

Teams also mix decimal and binary units casually, which makes logs and UI inconsistent. Decide which unit system you want and label it clearly.

Summary

  • Use Data.count to get the number of bytes in a Data value.
  • Convert to Double before dividing so fractional sizes are preserved.
  • Decide whether your output should be MB or MiB and label it consistently.
  • Use ByteCountFormatter for user-facing strings.
  • Do not use MemoryLayout<Data>.size to measure payload size.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.