Communitygithub.com

swift-actor-persistence

Swiftアクターモデルを用いたスレッドセーフなデータ永続化パターン。メモリキャッシュとファイルストレージを組み合わせ、コンパイル時にデータ競合を排除します。

swift-actor-persistence とは?

これはSwiftアクターモデルを活用してスレッドセーフなデータ永続化層を構築するためのスキルです。メモリ内キャッシュとファイルバックアップストレージを組み合わせ、コンパイラによってデータレースを排除します。Swift 5.5以降のオフラインファーストアプリや、複数の部分から同時にアクセスされる共有可変状態の管理に最適です。開発者は手動の同期機構(ロックやDispatchQueue)を一切記述する必要がなく、アクターが直列アクセスを保証します。Codable & Identifiableに準拠した任意のモデル型で再利用可能なジェネリックな設計であり、`@Observable` ViewModelと組み合わせてリアクティブなUI更新を実現できます。iOS/macOSアプリのローカルストレージ、ユーザーデータ、設定、キャッシュコンテンツなどに適用でき、レガシーなDispatchQueueベースのスレッドセーフを近代的なSwift並行性に置き換える際に特に有用です。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/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()
    }
}

主要な設計判断

判断根拠
Actor(class+ロックではない)コンパイラが強制するスレッドセーフ、手動同期不要
メモリキャッシュ+ファイル永続化キャッシュからの高速読み取り、ディスクへの耐久性のある書き込み
同期init読み込み非同期初期化の複雑さを回避
IDをキーとする辞書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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル