13.8 · UserDefaults surprises and FileManager essentials
The simplest storage is where many interview answers go wrong: what UserDefaults returns for a key that is not there, and the small rules for writing and replacing files.
Mental model. Know the defaults for missing values and the order of operations for files: write to a temporary file, then replace.
Small stores
UserDefaults behaviour and the FileManager basics.
- What does UserDefaults return for a key that is not set, how do registered defaults work, and what should and should not be stored there?
The typed getters never fail: integer(forKey:) returns 0, bool(forKey:) returns false and double(forKey:) returns 0.0 for a missing key, so you cannot tell… - What are the FileManager basics for saving a document: creating directories, replacing a file, and the resource values you set on it?
Three small rules prevent most file bugs. First, the directory must exist: writing to …/missing/sub/file fails (the check reports a cocoa error, code 4, “no…
More in Persistence & data
- 13.1 · Where data belongs, and the Keychain
- 13.2 · SQLite fundamentals: transactions, WAL, constraints, indexes and migrations
- 13.3 · The Core Data stack, contexts and faults, concurrency, and migrations
- 13.4 · SwiftData: models, contexts, predicates, actors and schema evolution
- 13.5 · The repository pattern and cache design
- 13.6 · Crashes mid-write, integrity, backups and data protection
- 13.7 · Syncing data across devices: conflicts, tombstones and CloudKit
- 13.9 · Reading query plans, typing and NULL, WAL locking, savepoints and full-text search
- 13.10 · Merge conflicts, faults and batch requests, delete rules, and the SwiftData context
- 13.11 · Keychain status codes, detecting corruption, an LRU cache and library trade-offs