Communitygithub.com

swift-actor-persistence

Swiftアクターを使用したスレッドセーフなデータ永続化 — メモリキャッシュとファイルバックアップストレージを組み合わせ、設計段階でデータ競合を排除します。Swiftでのデータ永続化や、データ競合・スレッドセーフの問題を設計から排除したい場合に使用します。

swift-actor-persistence とは?

このスキルは、Swift 5.5以降のアクターモデルを活用して、スレッドセーフなデータ永続化レイヤーを構築するためのパターンを提供します。メモリ内キャッシュとファイルバックアップストレージを組み合わせることで、高速な読み取りと耐久性のある書き込みを実現し、アクターモデルによってコンパイル時にデータ競合を排除します。`LocalRepository<T>` というジェネリックアクターを中心に設計されており、`Codable & Identifiable` に準拠した任意のモデル型で再利用可能です。このパターンは、iOS/macOSアプリのローカルデータ保存、オフラインファーストアーキテクチャ、さらに従来の `DispatchQueue` ベースのスレッドセーフコードを最新のSwift並行性に移行する場合に特に有効です。関連するプラットフォームとしては、Claude Code, Cursor, CodexなどのAIエージェントツールが想定されます。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Swiftアクターによるスレッドセーフな永続化

Swiftアクターを使用してスレッドセーフなデータ永続化レイヤーを構築するためのパターン。メモリ内キャッシュとファイルバックアップストレージを組み合わせ、アクターモデルを活用してコンパイル時にデータ競合を排除します。

アクティベーションのタイミング

  • Swift 5.5+ でデータ永続化レイヤーを構築する場合
  • 共有された可変状態へのスレッドセーフなアクセスが必要な場合
  • 手動同期(ロック、DispatchQueue)を排除したい場合
  • ローカルストレージを使用したオフラインファーストアプリを構築する場合

コアパターン

アクターベースのリポジトリ

アクターモデルはシリアル化されたアクセスを保証します — データ競合はなく、コンパイラによって強制されます。

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 中の同期ロード(アクター分離はまだアクティブではない)
        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) })
    }
}

使用法

アクター分離により、すべての呼び出しは自動的に非同期になります:

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

主要な設計上の決定

決定根拠
アクター(class + lock ではない)コンパイラによるスレッドセーフの強制、手動同期不要
メモリキャッシュ + ファイル永続化キャッシュからの高速読み取り、ディスクへの耐久性のある書き込み
同期 init ロード非同期初期化の複雑さを回避
ID をキーにした辞書識別子による O(1) ルックアップ
Codable & Identifiable でジェネリック任意のモデル型で再利用可能
アトミックファイル書き込み(.atomic)クラッシュ時の部分書き込みを防止

ベストプラクティス

  • Sendable 型を使用する — アクター境界を越えるすべてのデータに対して
  • アクターの公開APIは最小限に保つ — ドメイン操作のみを公開し、永続化の詳細は公開しない
  • .atomic 書き込みを使用する — アプリが書き込み中にクラッシュした場合のデータ破損を防ぐ
  • init では同期的にロードする — 非同期イニシャライザはローカルファイルに対しては複雑さを増すだけで利点が少ない
  • @Observable ViewModel と組み合わせる — リアクティブなUI更新のために

避けるべきアンチパターン

  • 新しいSwift並行性コードでアクターの代わりに DispatchQueue や NSLock を使用する
  • 内部キャッシュ辞書を外部呼び出し元に公開する
  • バリデーションなしでファイルURLを設定可能にする
  • すべてのアクターメソッド呼び出しが await であることを忘れる — 呼び出し元は非同期コンテキストを処理する必要がある
  • nonisolated を使用してアクター分離をバイパスする(目的を損なう)

使用すべきタイミング

  • iOS/macOSアプリでのローカルデータ保存(ユーザーデータ、設定、キャッシュコンテンツ)
  • 後でサーバーと同期するオフラインファーストアーキテクチャ
  • アプリの複数の部分が同時にアクセスする共有可変状態
  • 従来の DispatchQueue ベースのスレッドセーフを最新の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.

関連スキル