Loading...
Loading...
Use when building a thread-safe data persistence layer in Swift using actors with in-memory cache and file storage.
npx skill4agent add shimo4228/claude-code-learned-skills swift-actor-persistencepublic actor LocalRepository {
private var cache: [String: Record] = [:]
private let cacheFileURL: URL
public init(directory: URL = .documentsDirectory) {
self.cacheFileURL = directory.appendingPathComponent("cache.json")
// Synchronous cache load during init (actor isolation not yet active)
// init中の同期キャッシュ読み込み(actor分離がまだアクティブでないため)
self.cache = Self.loadCacheSynchronously(from: cacheFileURL)
}
public func save(_ record: Record) throws {
cache[record.id] = record
try persistToFile()
}
public func loadAll() -> [Record] {
Array(cache.values)
}
public func find(by id: String) -> Record? {
cache[id]
}
private func persistToFile() throws {
let data = try JSONEncoder().encode(Array(cache.values))
try data.write(to: cacheFileURL)
}
private static func loadCacheSynchronously(from url: URL) -> [String: Record] {
guard let data = try? Data(contentsOf: url),
let records = try? JSONDecoder().decode([Record].self, from: data) else {
return [:]
}
return Dictionary(uniqueKeysWithValues: records.map { ($0.id, $0) })
}
}let repository = LocalRepository()
// All calls are async due to actor isolation
// actor分離により、すべての呼び出しは非同期
let records = await repository.loadAll()
try await repository.save(newRecord)
let found = await repository.find(by: "question-1")@Observable@ObservableSendableSendableFileBasedSyncManagerFileBasedSyncManager