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.
In this page:
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
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)
Login to try C/C++/Java/PHP code in the editor
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
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))")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting
import Foundationis required beforeFileManageris available. - Assuming a hardcoded file path will exist across every machine or sandbox; using a temporary directory is safer for portable examples.
- Forgetting many
FileManageroperations, like writing or reading a file's contents, can throw and need to be wrapped intry/do-catch.
Chapter Summary
FileManager.defaultprovides access to file-system operations like checking existence, creating, and deleting files.FileManager.default.temporaryDirectorygives 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: