[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72Y884JKAMTE2MZA4RW4SF8":3,"skill-same:01M72Y884JKAMTE2MZA4RW4SF8":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M72Y884JKAMTE2MZA4RW4SF8","swift-actor-persistence",null,"在 Swift 中使用 actor 实现线程安全的数据持久化——基于内存缓存与文件支持的存储，通过设计消除数据竞争。","SriramGandhiS\u002FSkills","SriramGandhiS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211849986?v=4","01M72WQCW12BYX71C6WN584TTA","Sriram S","01M72WQCWTJ2RD0ET1X31AF1RC",1,"MIT","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Feverything-claude-code\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fswift-actor-persistence\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: swift-actor-persistence\ndescription: 在 Swift 中使用 actor 实现线程安全的数据持久化——基于内存缓存与文件支持的存储，通过设计消除数据竞争。\norigin: ECC\n---\n\n# 用于线程安全持久化的 Swift Actor\n\n使用 Swift actor 构建线程安全数据持久化层的模式。结合内存缓存与文件支持的存储，利用 actor 模型在编译时消除数据竞争。\n\n## 何时激活\n\n* 在 Swift 5.5+ 中构建数据持久化层\n* 需要对共享可变状态进行线程安全访问\n* 希望消除手动同步（锁、DispatchQueue）\n* 构建具有本地存储的离线优先应用\n\n## 核心模式\n\n### 基于 Actor 的存储库\n\nActor 模型保证了序列化访问 —— 没有数据竞争，由编译器强制执行。\n\n```swift\npublic actor LocalRepository\u003CT: Codable & Identifiable> where T.ID == String {\n    private var cache: [String: T] = [:]\n    private let fileURL: URL\n\n    public init(directory: URL = .documentsDirectory, filename: String = \"data.json\") {\n        self.fileURL = directory.appendingPathComponent(filename)\n        \u002F\u002F Synchronous load during init (actor isolation not yet active)\n        self.cache = Self.loadSynchronously(from: fileURL)\n    }\n\n    \u002F\u002F MARK: - Public API\n\n    public func save(_ item: T) throws {\n        cache[item.id] = item\n        try persistToFile()\n    }\n\n    public func delete(_ id: String) throws {\n        cache[id] = nil\n        try persistToFile()\n    }\n\n    public func find(by id: String) -> T? {\n        cache[id]\n    }\n\n    public func loadAll() -> [T] {\n        Array(cache.values)\n    }\n\n    \u002F\u002F MARK: - Private\n\n    private func persistToFile() throws {\n        let data = try JSONEncoder().encode(Array(cache.values))\n        try data.write(to: fileURL, options: .atomic)\n    }\n\n    private static func loadSynchronously(from url: URL) -> [String: T] {\n        guard let data = try? Data(contentsOf: url),\n              let items = try? JSONDecoder().decode([T].self, from: data) else {\n            return [:]\n        }\n        return Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) })\n    }\n}\n```\n\n### 用法\n\n由于 actor 隔离，所有调用都会自动变为异步：\n\n```swift\nlet repository = LocalRepository\u003CQuestion>()\n\n\u002F\u002F Read — fast O(1) lookup from in-memory cache\nlet question = await repository.find(by: \"q-001\")\nlet allQuestions = await repository.loadAll()\n\n\u002F\u002F Write — updates cache and persists to file atomically\ntry await repository.save(newQuestion)\ntry await repository.delete(\"q-001\")\n```\n\n### 与 @Observable ViewModel 结合使用\n\n```swift\n@Observable\nfinal class QuestionListViewModel {\n    private(set) var questions: [Question] = []\n    private let repository: LocalRepository\u003CQuestion>\n\n    init(repository: LocalRepository\u003CQuestion> = LocalRepository()) {\n        self.repository = repository\n    }\n\n    func load() async {\n        questions = await repository.loadAll()\n    }\n\n    func add(_ question: Question) async throws {\n        try await repository.save(question)\n        questions = await repository.loadAll()\n    }\n}\n```\n\n## 关键设计决策\n\n| 决策 | 理由 |\n|----------|-----------|\n| Actor（而非类 + 锁） | 编译器强制执行的线程安全性，无需手动同步 |\n| 内存缓存 + 文件持久化 | 从缓存中快速读取，持久化写入磁盘 |\n| 同步初始化加载 | 避免异步初始化的复杂性 |\n| 按 ID 键控的字典 | 按标识符进行 O(1) 查找 |\n| 泛型化 `Codable & Identifiable` | 可在任何模型类型中重复使用 |\n| 原子文件写入 (`.atomic`) | 防止崩溃时部分写入 |\n\n## 最佳实践\n\n* **对所有跨越 actor 边界的数据使用 `Sendable` 类型**\n* **保持 actor 的公共 API 最小化** —— 仅暴露领域操作，而非持久化细节\n* **使用 `.atomic` 写入** 以防止应用在写入过程中崩溃导致数据损坏\n* **在 `init` 中同步加载** —— 异步初始化器会增加复杂性，而对本地文件的益处微乎其微\n* **与 `@Observable` ViewModel 结合使用** 以实现响应式 UI 更新\n\n## 应避免的反模式\n\n* 在 Swift 并发新代码中使用 `DispatchQueue` 或 `NSLock` 而非 actor\n* 将内部缓存字典暴露给外部调用者\n* 在不进行验证的情况下使文件 URL 可配置\n* 忘记所有 actor 方法调用都是 `await` —— 调用者必须处理异步上下文\n* 使用 `nonisolated` 来绕过 actor 隔离（违背了初衷）\n\n## 何时使用\n\n* iOS\u002FmacOS 应用中的本地数据存储（用户数据、设置、缓存内容）\n* 稍后同步到服务器的离线优先架构\n* 应用中多个部分并发访问的任何共享可变状态\n* 用现代 Swift 并发性替换基于 `DispatchQueue` 的旧式线程安全机制\n","# 用于线程安全持久化的 Swift Actor\n\n使用 Swift actor 构建线程安全数据持久化层的模式。结合内存缓存与文件支持的存储，利用 actor 模型在编译时消除数据竞争。\n\n## 何时激活\n\n* 在 Swift 5.5+ 中构建数据持久化层\n* 需要对共享可变状态进行线程安全访问\n* 希望消除手动同步（锁、DispatchQueue）\n* 构建具有本地存储的离线优先应用\n\n## 核心模式\n\n### 基于 Actor 的存储库\n\nActor 模型保证了序列化访问 —— 没有数据竞争，由编译器强制执行。\n\n```swift\npublic actor LocalRepository\u003CT: Codable & Identifiable> where T.ID == String {\n    private var cache: [String: T] = [:]\n    private let fileURL: URL\n\n    public init(directory: URL = .documentsDirectory, filename: String = \"data.json\") {\n        self.fileURL = directory.appendingPathComponent(filename)\n        \u002F\u002F Synchronous load during init (actor isolation not yet active)\n        self.cache = Self.loadSynchronously(from: fileURL)\n    }\n\n    \u002F\u002F MARK: - Public API\n\n    public func save(_ item: T) throws {\n        cache[item.id] = item\n        try persistToFile()\n    }\n\n    public func delete(_ id: String) throws {\n        cache[id] = nil\n        try persistToFile()\n    }\n\n    public func find(by id: String) -> T? {\n        cache[id]\n    }\n\n    public func loadAll() -> [T] {\n        Array(cache.values)\n    }\n\n    \u002F\u002F MARK: - Private\n\n    private func persistToFile() throws {\n        let data = try JSONEncoder().encode(Array(cache.values))\n        try data.write(to: fileURL, options: .atomic)\n    }\n\n    private static func loadSynchronously(from url: URL) -> [String: T] {\n        guard let data = try? Data(contentsOf: url),\n              let items = try? JSONDecoder().decode([T].self, from: data) else {\n            return [:]\n        }\n        return Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) })\n    }\n}\n```\n\n### 用法\n\n由于 actor 隔离，所有调用都会自动变为异步：\n\n```swift\nlet repository = LocalRepository\u003CQuestion>()\n\n\u002F\u002F Read — fast O(1) lookup from in-memory cache\nlet question = await repository.find(by: \"q-001\")\nlet allQuestions = await repository.loadAll()\n\n\u002F\u002F Write — updates cache and persists to file atomically\ntry await repository.save(newQuestion)\ntry await repository.delete(\"q-001\")\n```\n\n### 与 @Observable ViewModel 结合使用\n\n```swift\n@Observable\nfinal class QuestionListViewModel {\n    private(set) var questions: [Question] = []\n    private let repository: LocalRepository\u003CQuestion>\n\n    init(repository: LocalRepository\u003CQuestion> = LocalRepository()) {\n        self.repository = repository\n    }\n\n    func load() async {\n        questions = await repository.loadAll()\n    }\n\n    func add(_ question: Question) async throws {\n        try await repository.save(question)\n        questions = await repository.loadAll()\n    }\n}\n```\n\n## 关键设计决策\n\n| 决策 | 理由 |\n|----------|-----------|\n| Actor（而非类 + 锁） | 编译器强制执行的线程安全性，无需手动同步 |\n| 内存缓存 + 文件持久化 | 从缓存中快速读取，持久化写入磁盘 |\n| 同步初始化加载 | 避免异步初始化的复杂性 |\n| 按 ID 键控的字典 | 按标识符进行 O(1) 查找 |\n| 泛型化 `Codable & Identifiable` | 可在任何模型类型中重复使用 |\n| 原子文件写入 (`.atomic`) | 防止崩溃时部分写入 |\n\n## 最佳实践\n\n* **对所有跨越 actor 边界的数据使用 `Sendable` 类型**\n* **保持 actor 的公共 API 最小化** —— 仅暴露领域操作，而非持久化细节\n* **使用 `.atomic` 写入** 以防止应用在写入过程中崩溃导致数据损坏\n* **在 `init` 中同步加载** —— 异步初始化器会增加复杂性，而对本地文件的益处微乎其微\n* **与 `@Observable` ViewModel 结合使用** 以实现响应式 UI 更新\n\n## 应避免的反模式\n\n* 在 Swift 并发新代码中使用 `DispatchQueue` 或 `NSLock` 而非 actor\n* 将内部缓存字典暴露给外部调用者\n* 在不进行验证的情况下使文件 URL 可配置\n* 忘记所有 actor 方法调用都是 `await` —— 调用者必须处理异步上下文\n* 使用 `nonisolated` 来绕过 actor 隔离（违背了初衷）\n\n## 何时使用\n\n* iOS\u002FmacOS 应用中的本地数据存储（用户数据、设置、缓存内容）\n* 稍后同步到服务器的离线优先架构\n* 应用中多个部分并发访问的任何共享可变状态\n* 用现代 Swift 并发性替换基于 `DispatchQueue` 的旧式线程安全机制\n",{"name":5,"origin":24,"description":7},"ECC","master","d6ca01da0f24a3b0e26e4a8b7b66cbd25d429f5d","everything-claude-code\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fswift-actor-persistence",0,"https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills","https:\u002F\u002Fgithub.com\u002FSriramGandhiS","https:\u002F\u002Fsriram.website\u002F","Curious guy who keeps tinkering until something works","2026-05-20 16:21:34",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add SriramGandhiS\u002FSkills --skill swift-actor-persistence",{"tool":40,"command":41},"bunx","bunx skills add SriramGandhiS\u002FSkills --skill swift-actor-persistence",{"tool":43,"command":44},"pnpm","pnpm dlx skills add SriramGandhiS\u002FSkills --skill swift-actor-persistence","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Feverything-claude-code\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fswift-actor-persistence\u002FSKILL.md",true,[],[49,57,62,68,75,82],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":56},"01M732609EPJWV13PVTX3GT4TM","webgpu-threejs-tsl","Comprehensive guide for developing WebGPU-enabled Three.js applications using TSL (Three.js Shading Language). Covers WebGPU renderer setup, TSL syntax and node materials, compute shaders, post-processing effects, and WGSL integration. Use this skill when working with Three.js WebGPU, TSL shaders, node materials, or GPU compute in Three.js.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fwebgpu-threejs-tsl\u002Fskills\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":58,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":56},"01M7325XM47AGWB6K6C4VXKE6B","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":56},"01M7325WP6DES69JKC840VMFEP","verification-loop","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":56},"01M7325TFQF1DZTQ6J3WGQQ1VR","tdd-workflow","Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Ftdd-workflow\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":56},"01M7325RGV9AY9PK92D2V8KKPW","strategic-compact","Suggests manual context compaction at logical intervals to preserve context through task phases rather than arbitrary auto-compaction.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fstrategic-compact\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":56},"01M7325MZC28SE86E7NMCNEFS4","security-review","Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment\u002Fsensitive features. Provides comprehensive security checklist and patterns.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fsecurity-review\u002FSKILL.md",[],[]]