← Back to Swift Course | Chapter 14: Standard Library & Best Practices | Lesson 4 of 7

FileManager Basics

FileManager is Swift's helper for finding, creating, and reading files on the computer, like a librarian who knows where everything is kept.

Writing and Reading a File

A String can be written directly to a file URL, and later read back using the matching initializer, both of which can throw if something goes wrong.

Example: Writing and Reading a File

markup
import Foundation
let tempDir = FileManager.default.temporaryDirectory
let fileURL = tempDir.appendingPathComponent("swift_demo.txt")
try! "Hello from Swift".write(to: fileURL, atomically: true, encoding: .utf8)
let contents = try! String(contentsOf: fileURL, encoding: .utf8)
print(contents)

Checking If a File Exists

FileManager.default.fileExists(atPath:) checks whether a given path currently points to an existing file or directory.

Example: Checking If a File Exists

markup
import Foundation
let tempDir = FileManager.default.temporaryDirectory
let fileURL = tempDir.appendingPathComponent("check_me.txt")
print("Exists before write: \(FileManager.default.fileExists(atPath: fileURL.path))")
try! "data".write(to: fileURL, atomically: true, encoding: .utf8)
print("Exists after write: \(FileManager.default.fileExists(atPath: fileURL.path))")
Common Mistakes
  1. Forgetting import Foundation is required before FileManager is available.
  2. Assuming a hardcoded file path will exist across every machine or sandbox; using a temporary directory is safer for portable examples.
  3. Forgetting many FileManager operations, like writing or reading a file's contents, can throw and need to be wrapped in try/do-catch.
Chapter Summary
  • FileManager.default provides access to file-system operations like checking existence, creating, and deleting files.
  • FileManager.default.temporaryDirectory gives a safe, writable location for scratch files.
  • Writing and reading file contents uses String(contentsOf:)/.write(to:...), which can throw errors.
  • .fileExists(atPath:) checks whether a given path currently exists.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.