Communitygithub.com

Swift 演员持久化

使用 Swift 中的 actor 实现线程安全的数据持久化——内存缓存与文件存储相结合,从根本上消除数据竞争。在 Swift 中持久化数据且需要设计避免数据竞争或线程安全问题时使用。

Swift 演员持久化 是什么?

此技能提供了一种结合内存缓存与文件存储、利用 Swift actor 模型实现线程安全数据持久化的模式。它通过编译器强制串行化访问来消除数据竞争,无需手动同步(如锁或调度队列)。该模式支持任何遵循 `Codable & Identifiable` 协议的类型,并基于 actor 隔离自动使所有操作为异步。它特别适用于构建离线优先应用、本地存储用户数据或设置,以及在多个并发访问部分替换旧的基于调度队列的线程安全方案。最佳实践包括使用 `Sendable` 类型、保持公共 API 最小化以及使用原子写入防止数据损坏。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/swift-actor-persistence

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Swift Actor 实现线程安全持久化

使用 Swift actor 构建线程安全数据持久化层的模式。结合内存缓存与文件存储,利用 actor 模型在编译时消除数据竞争。

何时激活

  • 在 Swift 5.5+ 中构建数据持久化层
  • 需要对共享可变状态进行线程安全访问
  • 希望消除手动同步(锁、调度队列)
  • 构建具有本地存储的离线优先应用

核心模式

基于 Actor 的仓库

Actor 模型保证串行化访问——无数据竞争,由编译器强制执行。

public actor LocalRepository<T: Codable & Identifiable> where T.ID == String {
    private var cache: [String: T] = [:]
    private let fileURL: URL

    public init(directory: URL = .documentsDirectory, filename: String = "data.json") {
        self.fileURL = directory.appendingPathComponent(filename)
        // 在 init 期间同步加载(actor 隔离尚未激活)
        self.cache = Self.loadSynchronously(from: fileURL)
    }

    // MARK: - 公共 API

    public func save(_ item: T) throws {
        cache[item.id] = item
        try persistToFile()
    }

    public func delete(_ id: String) throws {
        cache[id] = nil
        try persistToFile()
    }

    public func find(by id: String) -> T? {
        cache[id]
    }

    public func loadAll() -> [T] {
        Array(cache.values)
    }

    // MARK: - 私有

    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) -> [String: 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) })
    }
}

使用方式

由于 actor 隔离,所有调用自动变为异步:

let repository = LocalRepository<Question>()

// 读取——O(1) 快速查找,来自内存缓存
let question = await repository.find(by: "q-001")
let allQuestions = await repository.loadAll()

// 写入——原子性更新缓存并持久化到文件
try await repository.save(newQuestion)
try await repository.delete("q-001")

结合 @Observable ViewModel

@Observable
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()
    }
}

关键设计决策

决策理由
Actor(非 类 + 锁)编译器强制线程安全,无需手动同步
内存缓存 + 文件持久化快速读取来自缓存,持久写入到磁盘
同步初始化加载避免异步初始化复杂性
以 ID 为键的字典O(1) 标识符查找
泛型约束 Codable & Identifiable可跨任意模型类型重用
原子文件写入 (.atomic)防止崩溃时部分写入

最佳实践

  • 对所有跨 actor 边界的数据使用 Sendable 类型
  • 保持 actor 的公共 API 最小化——仅暴露领域操作,不暴露持久化细节
  • 使用 .atomic 写入以防止应用在写入过程中崩溃时数据损坏
  • 在 init 中同步加载——异步初始化器增加复杂性,对本地文件益处有限
  • 与 @Observable ViewModel 结合实现响应式 UI 更新

应避免的反模式

  • 在新的 Swift 并发代码中使用 DispatchQueue 或 NSLock 替代 actors
  • 将内部缓存字典暴露给外部调用者
  • 使文件 URL 可配置而不加验证
  • 忘记所有 actor 方法调用都需要 await——调用者必须处理异步上下文
  • 使用 nonisolated 绕过 actor 隔离(违背目的)

适用场景

  • iOS/macOS 应用中的本地数据存储(用户数据、设置、缓存内容)
  • 离线优先架构,后续同步到服务器
  • 应用中多个并发部分访问的任何共享可变状态
  • 用现代 Swift 并发替换旧的基于调度队列的线程安全方案

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

相关技能