Loading...
Loading...
Thread-safe data persistence in Swift using actors — in-memory cache with file-backed storage. Use when building local storage layers, offline-first patterns, or any shared mutable state that needs both concurrency safety and disk persistence.
npx skill4agent add kmshdev/claude-swift-toolkit swift-actor-persistenceswift-concurrencyswift-networkingDispatchQueuepublic actor LocalRepository<T: Codable & Identifiable> where T.ID: Hashable & Codable {
private var cache: [T.ID: T] = [:]
private let fileURL: URL
public init(directory: URL = .documentsDirectory, filename: String = "data.json") {
self.fileURL = directory.appendingPathComponent(filename)
self.cache = Self.loadSynchronously(from: fileURL)
}
// MARK: - Public API
public func save(_ item: T) throws {
cache[item.id] = item
try persistToFile()
}
public func delete(_ id: T.ID) throws {
cache[id] = nil
try persistToFile()
}
public func find(by id: T.ID) -> T? {
cache[id]
}
public func loadAll() -> [T] {
Array(cache.values)
}
// MARK: - Private
private func persistToFile() throws {
let data = try JSONEncoder().encode(Array(cache.values))
try data.write(to: fileURL, options: .atomic)
}
private static func loadSynchronously(from url: URL) -> [T.ID: T] {
guard let data = try? Data(contentsOf: url),
let items = try? JSONDecoder().decode([T].self, from: data) else {
return [:]
}
return Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) })
}
}let repo = LocalRepository<Question>(filename: "questions.json")
let question = await repo.find(by: questionID) // O(1) cache lookup
let all = await repo.loadAll()
try await repo.save(newQuestion) // updates cache + persists
try await repo.delete(questionID)@Observable @MainActor
final class QuestionListViewModel {
private(set) var questions: [Question] = []
private let repository: LocalRepository<Question>
init(repository: LocalRepository<Question> = LocalRepository()) {
self.repository = repository
}
func load() async {
questions = await repository.loadAll()
}
func add(_ question: Question) async throws {
try await repository.save(question)
questions = await repository.loadAll()
}
func remove(_ id: Question.ID) async throws {
try await repository.delete(id)
questions = await repository.loadAll()
}
}| Decision | Rationale |
|---|---|
| Actor (not class + lock) | Compiler-enforced thread safety, zero manual synchronization |
| In-memory cache + file persistence | Fast reads from cache, durable writes to disk |
| Synchronous init loading | Avoids async initialization complexity; actor isolation not yet active during |
| Dictionary keyed by ID | O(1) lookups by identifier |
Generic over | Reusable across any model type |
Atomic file writes ( | Prevents partial writes on crash |
DispatchQueueselfloadSynchronously@Observable @MainActor@Observable final class@MainActor@MainActorT.ID: Hashable & CodableT.ID == StringStringHashable & CodableUUIDIntData.write(to:)Data(contentsOf:)// Option 1: Offload to a non-cooperative thread
private func persistToFile() async throws {
let data = try JSONEncoder().encode(Array(cache.values))
let url = fileURL
try await Task.detached {
try data.write(to: url, options: .atomic)
}.value
}
// Option 2: Use SwiftData or Core Data for large datasets
// This pattern is best suited for lightweight local storageprivate struct VersionedStore<T: Codable>: Codable {
let version: Int
let items: [T]
}| Don't | Do Instead |
|---|---|
| Use actors — compiler-enforced, zero runtime overhead |
| Expose the internal cache dictionary | Only expose domain operations ( |
| Defeats the purpose — rethink the design |
| Call actor methods in a tight loop | Batch operations into a single actor method |
| Use for datasets > 10 MB | Switch to SwiftData, Core Data, or SQLite |
swift-concurrency@MainActorswift-networkingswift-app-lifecycletemplates/Repository.swiftRepositorySwiftDataRepository.swift@MainActorExampleModel.swift@ModelPersistenceController.swiftModelContainer