Working with the File System in Swift: A Practical Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction

\n

Working with the file system is one of the key tasks when developing applications for iOS and macOS. Whether you are writing an app to save user data, cache images, or export documents, understanding the basics of working with files in Swift is an essential skill. In this article, we will cover practical examples of working with the file system: creating, reading, writing, deleting files, and managing directories.

\n

Apple provides a powerful API FileManager that allows you to interact with the file system on both iOS and macOS. We will explore it with real-world examples and ready-to-use code.

\n\n

1. Getting Paths to System Directories

\n

Before starting to work with files, you need to access the correct directories. In iOS and macOS, each application runs in an isolated sandbox. Use the following paths for storing data:

\n\n

Documents Directory

\n

Used for storing user data that should persist across app updates and backups.

\n
import Foundation\n\nfunc getDocumentsDirectory() -> URL {\n    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)\n    return paths[0]\n}\n\n// Example usage\nlet documentsURL = getDocumentsDirectory()\nprint("Documents path: \\(documentsURL.path)")
\n\n

Caches Directory

\n

For temporary files that can be recreated (e.g., image cache).

\n
func getCachesDirectory() -> URL {\n    let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)\n    return paths[0]\n}
\n\n

Library/Application Support Directory

\n

For storing data that should not be directly accessible to the user but should persist.

\n
func getApplicationSupportDirectory() -> URL {\n    let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)\n    let directory = paths[0]\n    // Ensure the directory exists\n    try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)\n    return directory\n}
\n\n

2. Creating and Writing Files

\n

Now that we know where to store files, let's learn how to create them and write data.

\n\n

Writing Text Data

\n

The simplest way is to use the write(to:) method on a String or Data.

\n
func writeTextFile() {\n    let fileName = "example.txt"\n    let documentsURL = getDocumentsDirectory()\n    let fileURL = documentsURL.appendingPathComponent(fileName)\n    \n    let content = "Hello, Swift! This is a test file."\n    \n    do {\n        try content.write(to: fileURL, atomically: true, encoding: .utf8)\n        print("File successfully created: \\(fileURL.path)")\n    } catch {\n        print("Error writing file: \\(error.localizedDescription)")\n    }\n}
\n\n

Writing Binary Data (Images, JSON)

\n

For working with binary data, use Data.

\n
func writeJSONFile() {\n    let fileName = "data.json"\n    let documentsURL = getDocumentsDirectory()\n    let fileURL = documentsURL.appendingPathComponent(fileName)\n    \n    let dictionary: [String: Any] = [\n        "name": "Swift Developer",\n        "age": 30,\n        "skills": ["iOS", "macOS", "SwiftUI"]\n    ]\n    \n    do {\n        let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)\n        try jsonData.write(to: fileURL, options: .atomic)\n        print("JSON file saved")\n    } catch {\n        print("Error: \\(error)")\n    }\n}
\n\n

Creating Directories

\n

Sometimes you need to create nested folders to organize files.

\n
func createSubdirectories() {\n    let documentsURL = getDocumentsDirectory()\n    let subDirURL = documentsURL.appendingPathCo                

Blogs

Book Recommendations