| name | swift-actor-persistence |
| description | Thread-safe data persistence in Swift using actors — in-memory cache with file-backed storage, eliminating data races by design. |
| source_path | skills/swift-actor-persistence/SKILL.md |
| origin | ECC |
Swift Actors for Thread-Safe Persistence
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.
When to Activate
- Building a data persistence layer in Swift 5.5+
- Need thread-safe access to shared mutable state
- Want to eliminate manual synchronization (locks, DispatchQueues)
- Building offline-first apps with local storage
Core Pattern
Actor-Based Repository
The actor model guarantees serialized access — no data races, enforced by the compiler.
public actor LocalRepository<T: Codable & Identifiable> where T.ID == String {
private cache: [: ] [:]
fileURL:
(: .documentsDirectory, : ) {
.fileURL directory.appendingPathComponent(filename)
.cache .loadSynchronously(from: fileURL)
}
( : ) {
cache[item.id] item
persistToFile()
}
( : ) {
cache[id]
persistToFile()
}
( : ) -> ? {
cache[id]
}
() -> [] {
(cache.values)
}
() {
data ().encode((cache.values))
data.write(to: fileURL, options: .atomic)
}
( : ) -> [: ] {
data (contentsOf: url),
items ().decode([]., from: data) {
[:]
}
(uniqueKeysWithValues: items.map { (.id, ) })
}
}