xu-xiang/everything-claude-code-zh/swift-actor-persistence
Claude Code and agent skill by xu-xiang/everything-claude-code-zh
Trust tier 2
- community
Source check pending
Checking that the SKILL.md file is still in the repository.
Swift 中使用 actor 实现的线程安全数据持久化 —— 结合内存缓存与文件存储,从设计上消除数据竞争。
Install
npx vskill@latest install xu-xiang/everything-claude-code-zh/swift-actor-persistenceSKILL.md
使用 Swift Actors 实现线程安全持久化 (Swift Actors for Thread-Safe Persistence)
使用 Swift actor 构建线程安全数据持久化层的模式。该模式结合了内存缓存(In-memory caching)与基于文件的存储,利用 actor 模型(Actor model)在编译时消除数据竞争(Data races)。
何时启用
- 在 Swift 5.5+ 中构建数据持久化层
- 需要对共享可变状态(Shared mutable state)进行线程安全访问
- 希望消除手动同步操作(如 locks、DispatchQueues)
- 构建具有本地存储的离线优先(Offline-first)应用
核心模式 (Core Pattern)
基于 Actor 的仓库模式 (Actor-Based Repository)
Actor 模型保证了序列化访问(Serialized access)—— 由编译器强制执行,确保不会出现数据竞争。
使用方法 (Usage)
由于 actor 隔离(Actor isolation),所有调用都会自动变为异步:
结合 @Observable ViewModel
关键设计决策 (Key Design Decisions)
| 决策 | 理由 | |
|---|---|---|
| 使用 Actor (而非 class + lock) | 编译器强制执行线程安全,无需手动同步 | |
| 内存缓存 + 文件持久化 | 缓存提供快速读取,磁盘提供持久化写入 | |
| 在 init 中同步加载 | 避免异步初始化的复杂性,且对本地文件影响较小 | |
| 以 ID 为键的字典 (Dictionary) | 通过标识符进行 O(1) 查找 | |
泛型支持 Codable & Identifiable | 可在任何模型类型中复用 | |
原子化文件写入 (.atomic) | 防止崩溃时出现部分写入导致的数据损坏 |
最佳实践 (Best Practices)
- 对所有跨 actor 边界的数据使用 `Sendable` 类型
- 保持 actor 的公共 API 最小化 —— 仅暴露业务领域操作,不暴露持久化细节
- 使用 `.atomic` 写入 以防止应用在写入过程中崩溃导致数据损坏
- 在 `init` 中同步加载 —— 异步初始化会增加复杂性,而对本地文件的同步读取收益更高
- 结合 `@Observable` ViewModel 实现响应式 UI 更新
避免的反模式 (Anti-Patterns to Avoid)
- 在新的 Swift 并发代码中使用
DispatchQueue或NSLock而非 actor - 将内部缓存字典直接暴露给外部调用者
- 在没有验证的情况下让文件 URL 变为可配置
- 遗忘所有 actor 方法调用都是
await的 —— 调用者必须处理异步上下文 - 使用
nonisolated绕过 actor 隔离(这违背了使用 actor 的初衷)
适用场景 (When to Use)
- iOS/macOS 应用中的本地数据存储(用户数据、设置、缓存内容)
- 稍后与服务器同步的离线优先(Offline-first)架构
- 任何被应用多个部分并发访问的共享可变状态
- 使用现代 Swift 并发(Swift Concurrency)替换旧有的基于
DispatchQueue的线程安全方案
Security
- Security scanPassed, 96 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/swift-actor-persistence/SKILL.md
Popularity
- Repository stars
- 1,960
- Repository forks
- 325
- 7-day trend score
- 38
Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 21 Mar 2026, 7 months ago.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/xu-xiang/everything-claude-code-zh/swift-actor-persistence)