Communitygithub.com

Persistência com Ator em Swift

Persistência de dados thread-safe em Swift usando atores — cache em memória com armazenamento em arquivo, eliminando condições de corrida por design. Use ao persistir dados em Swift e um problema de condição de corrida ou thread-safety precisar ser eliminado.

O que é Persistência com Ator em Swift?

Esta skill implementa um padrão de persistência de dados thread-safe em Swift utilizando o modelo de atores, que garante acesso serializado a estado mutável compartilhado sem necessidade de sincronização manual (locks, DispatchQueues). Ela combina um cache em memória (para leituras rápidas O(1)) com armazenamento em arquivo (para gravações duráveis), tudo resolvido em tempo de compilação pelo compilador Swift. A skill é ideal para aplicativos iOS/macOS que precisam de armazenamento local offline-first, substituindo padrões legados baseados em DispatchQueue por concorrência moderna do Swift 5.5+. O código fornecido inclui um repositório genérico baseado em ator, exemplos de uso com ViewModels @Observable e decisões de design documentadas para evitar anti-padrões.

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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Atores Swift para Persistência Thread-Safe

Padrões para construir camadas de persistência de dados thread-safe usando atores Swift. Combina cache em memória com armazenamento em arquivo, aproveitando o modelo de ator para eliminar condições de corrida em tempo de compilação.

Quando Ativar

  • Construindo uma camada de persistência de dados em Swift 5.5+
  • Precisa de acesso thread-safe a estado mutável compartilhado
  • Quer eliminar sincronização manual (locks, DispatchQueues)
  • Construindo aplicativos offline-first com armazenamento local

Padrão Central

Repositório Baseado em Ator

O modelo de ator garante acesso serializado — sem condições de corrida, imposto pelo compilador.

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)
        // Carregamento síncrono durante init (isolamento do ator ainda não ativo)
        self.cache = Self.loadSynchronously(from: fileURL)
    }

    // MARK: - API Pública

    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: - Privado

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

Uso

Todas as chamadas são automaticamente assíncronas devido ao isolamento do ator:

let repository = LocalRepository<Question>()

// Leitura — busca O(1) rápida do cache em memória
let question = await repository.find(by: "q-001")
let allQuestions = await repository.loadAll()

// Escrita — atualiza o cache e persiste no arquivo atomicamente
try await repository.save(newQuestion)
try await repository.delete("q-001")

Combinando com ViewModel @Observable

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

Principais Decisões de Design

DecisãoJustificativa
Ator (não class + lock)Segurança de thread imposta pelo compilador, sem sincronização manual
Cache em memória + persistência em arquivoLeituras rápidas do cache, gravações duráveis no disco
Carregamento síncrono no initEvita complexidade de inicialização assíncrona
Dicionário indexado por IDBuscas O(1) por identificador
Genérico sobre Codable & IdentifiableReutilizável em qualquer tipo de modelo
Gravações atômicas (.atomic)Previne gravações parciais em caso de falha

Melhores Práticas

  • Use tipos Sendable para todos os dados que cruzam limites do ator
  • Mantenha a API pública do ator mínima — exponha apenas operações de domínio, não detalhes de persistência
  • Use gravações .atomic para evitar corrupção de dados se o aplicativo falhar no meio de uma gravação
  • Carregue sincronamente no init — inicializadores assíncronos adicionam complexidade com benefício mínimo para arquivos locais
  • Combine com ViewModels @Observable para atualizações reativas da interface

Anti-Padrões a Evitar

  • Usar DispatchQueue ou NSLock em vez de atores para novo código de concorrência Swift
  • Expor o dicionário de cache interno para chamadores externos
  • Tornar a URL do arquivo configurável sem validação
  • Esquecer que todas as chamadas de métodos do ator são await — chamadores devem lidar com contexto assíncrono
  • Usar nonisolated para contornar o isolamento do ator (derrota o propósito)

Quando Usar

  • Armazenamento local de dados em aplicativos iOS/macOS (dados do usuário, configurações, conteúdo em cache)
  • Arquiteturas offline-first que sincronizam com um servidor posteriormente
  • Qualquer estado mutável compartilhado que múltiplas partes do aplicativo acessam concorrentemente
  • Substituir segurança de thread baseada em DispatchQueue legada por concorrência Swift moderna

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.

Habilidades Relacionadas