Working with the File System in Swift: Basics for Beginners

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: For Beginners



Working with the file system is one of the key tasks when developing applications for iOS and macOS. Whether it's saving user data, caching images, or exporting documents, you will inevitably need to interact with files and folders. In this article, we will cover the basic Swift tools for working with the file system, including FileManager, directory paths, creating, reading, writing, and deleting files. The material is aimed at beginner developers, so all examples will be as simple and clear as possible.



Basics: FileManager and Paths



The main class for working with the file system in Swift is FileManager. It is a wrapper over standard system calls that provides a convenient interface for managing files and folders. Most often, its singleton is used:



let fileManager = FileManager.default


Since applications in iOS and macOS operate in an isolated environment (sandbox), you need to know where you can save data. The main directories that the application has access to are:



  • Documents — for user documents and data that should persist between launches.
  • Caches — for temporary files that the system can delete to free up space.
  • Temporary — for temporary files that are guaranteed to be deleted on the next device reboot.
  • Library/Application Support — for data that should not be directly accessible to the user but should persist.


You can get the path to the desired directory using the urls(for:in:) method:



// Get the path to the Documents folderlet documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!print("Documents path: \\(documentsURL.path)")

// Get the path to the Caches folderlet cachesURL = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!print("Caches path: \\(cachesURL.path)")

// Get the path to the temporary folderlet tempURL = fileManager.temporaryDirectoryprint("Temp path: \\(tempURL.path)")


Note: the method returns an array of URL (in case multiple paths exist), but for user directories, the first element is usually taken. In modern Swift, it is recommended to use URL rather than string paths, as it is safer and more convenient.



Creating and Writing Files



Now that we know where to save files, let's learn how to create them and write data to them. For writing text data, the easiest way is to use the write(to:atomically:encoding:) method of the String class:



// Create the path to the file in the Documents folderlet fileURL = documentsURL.appendingPathComponent("myFile.txt")

// Text to writelet content = "Hello, world! This is my first file in Swift."

do { // Write the string to the file try content.write(to: fileURL, atomically: true, encoding: .utf8) print("File successfully created: \\(fileURL.path)")} catch { print("Error writing file: \\(error.localizedDescription)")}


The parameter atomically: true means that the data will first be written to a temporary file and then renamed to the target file. This protects against file corruption in case of a crash. For binary data (e.g., images), you can use Data:



// Create binary data (e.g., an array of bytes)let data = Data([0x48, 0x65, 0x6C, 0x6C, 0x6F]) // "Hello" in ASCII

let binaryFileURL = documentsURL.appendingPathComponent("data.bin")

do { try data.write(to: binaryFileURL, options: .atomic) print("Binary file created")} catch { print("Error: \\(error)")}


Reading Files and P

Blogs

Book Recommendations