|
| 1 | +--- |
| 2 | +name: swift-actor-persistence |
| 3 | +description: Thread-safe data persistence in Swift using actors — in-memory cache with file-backed storage, eliminating data races by design. |
| 4 | +--- |
| 5 | + |
| 6 | +# Swift Actors for Thread-Safe Persistence |
| 7 | + |
| 8 | +Patterns for building thread-safe data persistence layers using Swift actors. Combines in-memory caching with file-backed storage, leveraging the actor model to eliminate data races at compile time. |
| 9 | + |
| 10 | +## When to Activate |
| 11 | + |
| 12 | +- Building a data persistence layer in Swift 5.5+ |
| 13 | +- Need thread-safe access to shared mutable state |
| 14 | +- Want to eliminate manual synchronization (locks, DispatchQueues) |
| 15 | +- Building offline-first apps with local storage |
| 16 | + |
| 17 | +## Core Pattern |
| 18 | + |
| 19 | +### Actor-Based Repository |
| 20 | + |
| 21 | +The actor model guarantees serialized access — no data races, enforced by the compiler. |
| 22 | + |
| 23 | +```swift |
| 24 | +public actor LocalRepository<T: Codable & Identifiable> where T.ID == String { |
| 25 | + private var cache: [String: T] = [:] |
| 26 | + private let fileURL: URL |
| 27 | + |
| 28 | + public init(directory: URL = .documentsDirectory, filename: String = "data.json") { |
| 29 | + self.fileURL = directory.appendingPathComponent(filename) |
| 30 | + // Synchronous load during init (actor isolation not yet active) |
| 31 | + self.cache = Self.loadSynchronously(from: fileURL) |
| 32 | + } |
| 33 | + |
| 34 | + // MARK: - Public API |
| 35 | + |
| 36 | + public func save(_ item: T) throws { |
| 37 | + cache[item.id] = item |
| 38 | + try persistToFile() |
| 39 | + } |
| 40 | + |
| 41 | + public func delete(_ id: String) throws { |
| 42 | + cache[id] = nil |
| 43 | + try persistToFile() |
| 44 | + } |
| 45 | + |
| 46 | + public func find(by id: String) -> T? { |
| 47 | + cache[id] |
| 48 | + } |
| 49 | + |
| 50 | + public func loadAll() -> [T] { |
| 51 | + Array(cache.values) |
| 52 | + } |
| 53 | + |
| 54 | + // MARK: - Private |
| 55 | + |
| 56 | + private func persistToFile() throws { |
| 57 | + let data = try JSONEncoder().encode(Array(cache.values)) |
| 58 | + try data.write(to: fileURL, options: .atomic) |
| 59 | + } |
| 60 | + |
| 61 | + private static func loadSynchronously(from url: URL) -> [String: T] { |
| 62 | + guard let data = try? Data(contentsOf: url), |
| 63 | + let items = try? JSONDecoder().decode([T].self, from: data) else { |
| 64 | + return [:] |
| 65 | + } |
| 66 | + return Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) }) |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
| 70 | + |
| 71 | +### Usage |
| 72 | + |
| 73 | +All calls are automatically async due to actor isolation: |
| 74 | + |
| 75 | +```swift |
| 76 | +let repository = LocalRepository<Question>() |
| 77 | + |
| 78 | +// Read — fast O(1) lookup from in-memory cache |
| 79 | +let question = await repository.find(by: "q-001") |
| 80 | +let allQuestions = await repository.loadAll() |
| 81 | + |
| 82 | +// Write — updates cache and persists to file atomically |
| 83 | +try await repository.save(newQuestion) |
| 84 | +try await repository.delete("q-001") |
| 85 | +``` |
| 86 | + |
| 87 | +### Combining with @Observable ViewModel |
| 88 | + |
| 89 | +```swift |
| 90 | +@Observable |
| 91 | +final class QuestionListViewModel { |
| 92 | + private(set) var questions: [Question] = [] |
| 93 | + private let repository: LocalRepository<Question> |
| 94 | + |
| 95 | + init(repository: LocalRepository<Question> = LocalRepository()) { |
| 96 | + self.repository = repository |
| 97 | + } |
| 98 | + |
| 99 | + func load() async { |
| 100 | + questions = await repository.loadAll() |
| 101 | + } |
| 102 | + |
| 103 | + func add(_ question: Question) async throws { |
| 104 | + try await repository.save(question) |
| 105 | + questions = await repository.loadAll() |
| 106 | + } |
| 107 | +} |
| 108 | +``` |
| 109 | + |
| 110 | +## Key Design Decisions |
| 111 | + |
| 112 | +| Decision | Rationale | |
| 113 | +|----------|-----------| |
| 114 | +| Actor (not class + lock) | Compiler-enforced thread safety, no manual synchronization | |
| 115 | +| In-memory cache + file persistence | Fast reads from cache, durable writes to disk | |
| 116 | +| Synchronous init loading | Avoids async initialization complexity | |
| 117 | +| Dictionary keyed by ID | O(1) lookups by identifier | |
| 118 | +| Generic over `Codable & Identifiable` | Reusable across any model type | |
| 119 | +| Atomic file writes (`.atomic`) | Prevents partial writes on crash | |
| 120 | + |
| 121 | +## Best Practices |
| 122 | + |
| 123 | +- **Use `Sendable` types** for all data crossing actor boundaries |
| 124 | +- **Keep the actor's public API minimal** — only expose domain operations, not persistence details |
| 125 | +- **Use `.atomic` writes** to prevent data corruption if the app crashes mid-write |
| 126 | +- **Load synchronously in `init`** — async initializers add complexity with minimal benefit for local files |
| 127 | +- **Combine with `@Observable`** ViewModels for reactive UI updates |
| 128 | + |
| 129 | +## Anti-Patterns to Avoid |
| 130 | + |
| 131 | +- Using `DispatchQueue` or `NSLock` instead of actors for new Swift concurrency code |
| 132 | +- Exposing the internal cache dictionary to external callers |
| 133 | +- Making the file URL configurable without validation |
| 134 | +- Forgetting that all actor method calls are `await` — callers must handle async context |
| 135 | +- Using `nonisolated` to bypass actor isolation (defeats the purpose) |
| 136 | + |
| 137 | +## When to Use |
| 138 | + |
| 139 | +- Local data storage in iOS/macOS apps (user data, settings, cached content) |
| 140 | +- Offline-first architectures that sync to a server later |
| 141 | +- Any shared mutable state that multiple parts of the app access concurrently |
| 142 | +- Replacing legacy `DispatchQueue`-based thread safety with modern Swift concurrency |
0 commit comments