Swift
File Size
Programming
iOS Development
File Handling

Get file size 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

Getting a file’s size in Swift is straightforward once you know which API you are asking. The main choice is whether you want simple metadata from the filesystem or you need a more specific measurement such as allocated size on disk.

Read File Size with FileManager

For a normal file path, FileManager can read the item attributes and extract the .size entry:

swift
1import Foundation
2
3func fileSize(atPath path: String) throws -> UInt64 {
4    let attributes = try FileManager.default.attributesOfItem(atPath: path)
5    guard let size = attributes[.size] as? NSNumber else {
6        throw NSError(domain: "FileSize", code: 1, userInfo: [
7            NSLocalizedDescriptionKey: "Size attribute missing"
8        ])
9    }
10    return size.uint64Value
11}
12
13let path = "/tmp/example.txt"
14
15do {
16    let size = try fileSize(atPath: path)
17    print("bytes:", size)
18} catch {
19    print("failed:", error)
20}

This is the most common answer when you already have a path string and want the logical file size in bytes.

Use URLResourceValues When You Already Have a File URL

If the rest of your code uses URL, it is cleaner to stay with URL-based APIs:

swift
1import Foundation
2
3func fileSize(for url: URL) throws -> Int {
4    let values = try url.resourceValues(forKeys: [.fileSizeKey])
5    guard let size = values.fileSize else {
6        throw NSError(domain: "FileSize", code: 2, userInfo: [
7            NSLocalizedDescriptionKey: "File size unavailable"
8        ])
9    }
10    return size
11}
12
13let url = URL(fileURLWithPath: "/tmp/example.txt")
14
15do {
16    let size = try fileSize(for: url)
17    print("bytes:", size)
18} catch {
19    print("failed:", error)
20}

This fits nicely in Swift codebases that already represent filesystem locations as URLs rather than raw paths.

Logical Size Versus Allocated Size

The value returned by .size or .fileSizeKey is usually the logical byte count of the file contents. That is not always the same as disk usage. Filesystems allocate storage in blocks, sparse files can behave differently, and compressed storage can change the physical usage story.

If you need the allocated size instead of the logical size, ask for a different resource key:

swift
1import Foundation
2
3func allocatedSize(for url: URL) throws -> Int {
4    let values = try url.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])
5    return values.totalFileAllocatedSize ?? values.fileAllocatedSize ?? 0
6}

That distinction matters in storage dashboards or cleanup tools where “how many bytes this file contains” and “how much disk space this file consumes” are not the same question.

Format the Result for Display

Raw byte counts are good for logic, but not ideal for user interfaces. For display, use ByteCountFormatter:

swift
1import Foundation
2
3let formatter = ByteCountFormatter()
4formatter.countStyle = .file
5
6let bytes: Int64 = 3_145_728
7print(formatter.string(fromByteCount: bytes))

This keeps the storage calculation separate from the user-facing formatting, which is a good habit in general.

Handle Missing Files and Directory Inputs

A file-size helper should usually decide what to do with directories. Some APIs can return a value for a directory entry, but that is not the same as recursively summing all contents inside the directory. If the caller really wants folder size, that is a different operation and should be implemented explicitly.

Also remember that sandboxed app environments may limit which paths are readable. A missing file and a permission failure are both common enough that the function should surface errors clearly rather than silently returning zero.

Common Pitfalls

The most common mistake is assuming a directory size request works the same as a file size request. It does not. Folder size usually means walking the contents recursively, not reading one attribute.

Another pitfall is mixing path strings and file URLs carelessly. Swift supports both, but code is easier to reason about when you stay consistent within one function or module.

It is also easy to forget the difference between logical size and allocated size. If a storage-management feature cares about real disk usage, .fileSizeKey alone may not tell the full story.

Finally, avoid swallowing filesystem errors and returning zero by default. A missing file and a zero-byte file are very different states and should not be conflated.

Summary

  • Use FileManager.attributesOfItem when you have a path string.
  • Use URL.resourceValues when the rest of the code works with file URLs.
  • Distinguish logical byte count from allocated disk usage.
  • Format byte counts with ByteCountFormatter only at the presentation layer.
  • Treat missing files, permission issues, and directories as separate cases instead of collapsing them into one fallback value.

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.