Working with the File System in Swift: A Complete 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

Working with the File System in Swift: A Complete Guide



Managing files and directories is one of the key tasks when developing applications for iOS and macOS. In Swift, the main tool for working with the file system is the FileManager class. In this article, we will cover how to create, read, write, move, and delete files, as well as how to efficiently manage directories. All code examples are written in Swift and are suitable for iOS and macOS projects.



FileManager Basics



FileManager is a singleton that provides an interface for interacting with the file system. To use it, simply get an instance:



let fileManager = FileManager.default


The class allows you to perform almost any operation: check file existence, get attributes, create folders, and much more. It is important to remember that all file system operations can throw errors, so we will use the do-catch construct.



Working with Directories



Before creating files, you need to learn how to manage folders. Let's look at the basic operations with directories.



Checking Directory Existence



let documentsPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!let newFolderPath = documentsPath.appendingPathComponent("MyFolder")

if fileManager.fileExists(atPath: newFolderPath.path) { print("Directory exists")} else { print("Directory not found")}


Creating a Directory



do {    try fileManager.createDirectory(at: newFolderPath,                                     withIntermediateDirectories: true,                                     attributes: nil)    print("Directory created")} catch {    print("Error creating directory: \\(error.localizedDescription)")}


The withIntermediateDirectories parameter allows you to automatically create all missing folders along the path. For example, if you want to create Folder1/Folder2/Folder3, and Folder1 does not exist — it will be created automatically.



Getting the Contents of a Directory



do {    let contents = try fileManager.contentsOfDirectory(at: documentsPath,                                                        includingPropertiesForKeys: nil)    for item in contents {        print("Found item: \\(item.lastPathComponent)")    }} catch {    print("Error reading directory: \\(error)")}


Reading and Writing Files



In Swift, there are several ways to write and read data. Let's look at the main ones.



Writing a Text File



let text = "Hello, world! This is a test file."let filePath = documentsPath.appendingPathComponent("test.txt")

do { try text.write(to: filePath, atomically: true, encoding: .utf8) print("File successfully written")} catch { print("Error writing: \\(error)")}


Reading a Text File



do {    let savedText = try String(contentsOf: filePath, encoding: .utf8)    print("File contents: \\(savedText)")} catch {    print("Error reading: \\(error)")}


Working with Binary Data



// Writinglet data = "Binary data example".data(using: .utf8)!let binaryPath = documentsPath.appendingPathComponent("data.bin")

do { try data.write(to: binaryPath, options: .atomic) print("Binary data written")} catch { print("Error writing data: \\(error)")}

// Readingdo { let loadedData = try Data(contentsOf: binaryPath) print("Read \\(loadedData.count) bytes")} catch { print("Error reading data: \\(error)")}


Moving, Copying, and Deleting Files



File management includes not only creation but also moving

Blogs

Book Recommendations