Lesson 8 of 9 · 27m
Persistence with SwiftData, Files, and Keychain
Choose the right storage layer for structured data, documents, caches, drafts, and secrets while planning migrations and deletion honestly.
Persistence questions sound simple until a user upgrades, reinstalls, loses connectivity, or asks support where a draft went. Storage is not one decision. Structured data, binary documents, cache material, preferences, drafts, and secrets have different durability and confidentiality requirements.
SwiftData is for object graphs, not everything
SwiftData gives you schema definitions, relationships, queries, and migrations with less ceremony than classic Core Data:
@Model
final class CachedDocument {
@Attribute(.unique) var id: UUID
var title: String
var updatedAt: Date
var bodyData: Data
init(id: UUID, title: String, updatedAt: Date, bodyData: Data) {
self.id = id
self.title = title
self.updatedAt = updatedAt
self.bodyData = bodyData
}
}Use it when you need querying, relationships, offline reads, or local mirrors of server state. Do not dump every JSON response into persistence because it feels responsible; invalidation and size limits are part of the design.
Model migration before you need it
Any shipped schema can become legacy data on a user's phone. Version schemas when necessary and test upgrade paths with real fixtures. A migration that works from version 3 to 4 but not 1 to 4 is an incident waiting for your oldest active devices.
Files are for documents and durable user artifacts
Use the app container intentionally:
let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let url = directory.appendingPathComponent("draft-\(id.uuidString).json")
try data.write(to: url, options: [.atomic])Atomic writes reduce corruption when the app is interrupted. The caches directory can be purged by the system; documents cannot be treated as disposable.
Keychain is for secrets, not a general database
Tokens, session keys, and cryptographic material belong in Keychain:
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "refresh-token",
kSecAttrService as String: "com.example.workspace",
kSecValueData as String: tokenData,
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
]
SecItemAdd(query as CFDictionary, nil)Use ThisDeviceOnly when a credential should not migrate through backups. Test logout and account switching so one user does not inherit another user's token.
Deletion is part of the model
Offline systems need tombstones, sync state, or server reconciliation. If a user deletes a document while offline, removing only the local copy may be wrong. Represent the operation explicitly:
local object state -> pending mutation -> server acknowledgement -> reconcile/delete local recordStorage bugs are usually consistency bugs wearing a database costume.
Field notes
- UserDefaults is for small preferences, not object graphs, large blobs, or secrets.
- Keep sensitive data out of plain files, logs, screenshots, analytics events, and crash breadcrumbs.
- Test migration with production-shaped data volume. Empty databases migrate beautifully.
- A cache with no eviction rule is just slow storage growth.
Was this lesson helpful?