Reading and writing files

Persistence Junior Swift 5.7+ iOS 17+ Reviewed By Alok Singh

Pick the fix

A draft must never be corrupted by a crash mid-write, and must be encrypted while the device is locked. Which write?

Options
Hint 1 of 1

Two requirements: atomic and protected.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A try data.write(to: url, options: [.atomic, .completeFileProtection])

Correct. It writes to a temporary file, swaps it in, and protects it.

Why not the others?
  • B try data.write(to: url). No atomicity, so a crash can leave a partial file.
  • C FileManager.default.createFile(atPath:contents:) every second. It's not atomic or protected, and wastes I/O.
  • D Save it in UserDefaults. It's not for documents and isn't protected.

30-second answer

Get a directory URL with URL.documentsDirectory (or applicationSupportDirectory or cachesDirectory), append a file name and write with data.write(to:options:). Use .atomic so a crash never leaves a half-written file, and a file protection option for sensitive data. Do large reads and writes off the main thread.

Practise saying it · 30 s. No recording, just a timer

Explain safe file writes.

Say your answer out loud, then check which of these points you covered:

  • Right directory
  • Atomic writes
  • File protection
  • Off main thread

Deep dive

Create Application Support before writing; it may not exist.

Use FileManager for moving, copying and checking existence.

Exclude re-downloadable files from backup with isExcludedFromBackup.

Use NSFileCoordinator for files shared with extensions.

Common mistakes

  • Writing without .atomic.
  • Hard-coding absolute paths; the container path changes.

Senior take & follow-ups

Seniors write atomically, choose protection and backup settings, and keep I/O off the main thread.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why not store absolute paths?

    Show hint

    The container path changes between installs and updates.

  2. What does .completeFileProtection do?

    Show hint

    The file is encrypted and unreadable while the device is locked.

Suggest a fix if something here is wrong or out of date.