Communitygithub.com

Swift Actor 持久化

使用 Swift Actor 實現執行緒安全的資料持久化 — 記憶體快取搭配檔案儲存,從設計上消除資料競爭。在 Swift 中需要持久化資料且需設計解決資料競爭或執行緒安全問題時使用。

Swift Actor 持久化 是什麼?

此技能提供使用 Swift Actor 建構執行緒安全資料持久化層的標準模式。它結合了記憶體快取與檔案備份儲存,利用 Actor 模型在編譯時消除資料競爭,無需手動同步(如鎖或 DispatchQueue)。主要適用於 Swift 5.5+ 的開發者,特別是建構離線優先應用程式或需要執行緒安全地存取共享可變狀態的情境。核心模式是一個泛型 Actor 儲存庫,支援 Codable 與 Identifiable 模型,提供 O(1) 的記憶體查找以及原子性檔案寫入,確保崩潰時資料完整性。此模式可與 @Observable ViewModel 無縫整合,實現響應式 UI 更新,並包含關鍵設計決策(如使用 Actor 而非類別加鎖、同步初始化載入)以及最佳實踐。技能也明確指出應避免的反模式,例如在新程式碼中使用 DispatchQueue 或 NSLock 取代 Actor,或使用 nonisolated 繞過 Actor 隔離。

相容平台~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+ 中建構資料持久化層
  • 需要執行緒安全地存取共享可變狀態
  • 希望消除手動同步(鎖、DispatchQueue)
  • 建構具有本地儲存的離線優先應用程式

核心模式

基於 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)
        // 初始化期間同步載入(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(而非 class + lock)編譯器強制執行執行緒安全,無需手動同步
記憶體快取 + 檔案持久化從快取快速讀取,寫入磁碟持久可靠
同步初始化載入避免非同步初始化的複雜性
以 ID 為鍵的字典按識別碼 O(1) 查詢
泛型 Codable & Identifiable可重複用於任何模型類型
原子性檔案寫入 (.atomic)防止崩潰時的部分寫入

最佳實踐

  • 使用 Sendable 類型 用於所有跨越 Actor 邊界的資料
  • 保持 Actor 的公開 API 最小化 — 只暴露領域操作,不暴露持久化細節
  • 使用 .atomic 寫入 以防止應用程式在寫入中途崩潰時資料損毀
  • 在 init 中同步載入 — 非同步初始化器會增加複雜性,對本地檔案好處不大
  • 搭配 @Observable ViewModel 以實現響應式 UI 更新

應避免的反模式

  • 在新的 Swift 並行程式碼中使用 DispatchQueue 或 NSLock 取代 Actor
  • 將內部快取字典暴露給外部呼叫者
  • 讓檔案 URL 可設定但未經驗證
  • 忘記所有 Actor 方法呼叫都需要 await — 呼叫者必須處理非同步上下文
  • 使用 nonisolated 繞過 Actor 隔離(違背目的)

使用時機

  • iOS/macOS 應用程式中的本地資料儲存(使用者資料、設定、快取內容)
  • 離線優先架構,後續同步到伺服器
  • 任何應用程式中多個部分同時存取的共享可變狀態
  • 用現代 Swift 並行取代舊式基於 DispatchQueue 的執行緒安全

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.

相關技能