본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)280k · #249

swift-actor-persistence

하는 일

이 코드는 앱의 여러 부분이 동시에 접근하더라도 중요한 정보를 안전하게 저장하도록 돕습니다. 빠른 접근을 위해 데이터를 메모리에 보관하고, 손실을 막기 위해 파일에도 저장합니다.

사용하는 경우

  • ✓앱에 사용자 데이터를 저장할 때.
  • ✓인터넷 없이도 작동하는 앱을 만들 때.
  • ✓여러 곳에서 동시에 접근할 때 데이터가 손상되지 않도록 막을 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/swift-actor-persistence/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/swift-actor-persistence/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“이 앱에서 사용자 설정을 저장해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

‘액터’라는 기법을 사용해 한 번에 하나의 코드만 데이터를 수정하도록 보장하여 혼란과 오류를 막습니다. 데이터는 속도를 위해 메모리에 보관하고, 지속성을 위해 파일에 저장합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Swift Actors for Thread-Safe Persistence

Patterns for building thread-safe data persistence layers using Swift actors. Combines in-memory caching with file-backed storage, leveraging the actor model to eliminate data races at compile time.

When to Activate

  • Building a data persistence layer in Swift 5.5+
  • Need thread-safe access to shared mutable state
  • Want to eliminate manual synchronization (locks, DispatchQueues)
  • Building offline-first apps with local storage

Core Pattern

Actor-Based Repository

The actor model guarantees serialized access — no data races, enforced by the compiler.

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)
        // Synchronous load during init (actor isolation not yet active)
        self.cache = Self.loadSynchronously(from: fileURL)
    }

    // MARK: - Public 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

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

Usage

All calls are automatically async due to actor isolation:

let repository = LocalRepository<Question>()

// Read — fast O(1) lookup from in-memory cache
let question = await repository.find(by: "q-001")
let allQuestions = await repository.loadAll()

// Write — updates cache and persists to file atomically
try await repository.save(newQuestion)
try await repository.delete("q-001")

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

Key Design Decisions

Decision Rationale
Actor (not class + lock) Compiler-enforced thread safety, no manual synchronization
In-memory cache + file persistence Fast reads from cache, durable writes to disk
Synchronous init loading Avoids async initialization complexity
Dictionary keyed by ID O(1) lookups by identifier
Generic over Codable & Identifiable Reusable across any model type
Atomic file writes (.atomic) Prevents partial writes on crash

Best Practices

  • Use Sendable types for all data crossing actor boundaries
  • Keep the actor's public API minimal — only expose domain operations, not persistence details
  • Use .atomic writes to prevent data corruption if the app crashes mid-write
  • Load synchronously in init — async initializers add complexity with minimal benefit for local files
  • Combine with @Observable ViewModels for reactive UI updates

Anti-Patterns to Avoid

  • Using DispatchQueue or NSLock instead of actors for new Swift concurrency code
  • Exposing the internal cache dictionary to external callers
  • Making the file URL configurable without validation
  • Forgetting that all actor method calls are await — callers must handle async context
  • Using nonisolated to bypass actor isolation (defeats the purpose)

When to Use

  • Local data storage in iOS/macOS apps (user data, settings, cached content)
  • Offline-first architectures that sync to a server later

…

자주 묻는 질문

일반 메서드 대신 ‘액터’를 쓰는 이유는 무엇인가요?

액터는 데이터에 접근하는 코드가 한 번에 하나씩 실행되도록 자동으로 보장합니다. 여러 부분이 동시에 같은 값을 바꿀 때 생기는 ‘데이터 레이스’ 오류를 막습니다.

‘지속성(persistence)’이란 무엇인가요?

앱을 닫거나 다시 시작해도 정보가 사라지지 않도록 저장하는 것입니다. 컴퓨터에 문서를 저장하는 것과 같습니다.

데이터는 어떻게 저장되나요?

데이터는 JSON 파일에 저장됩니다. 쓰기 작업이 한 번에 끝나도록 ‘원자적으로(atomically)’ 저장되므로, 저장 중에 앱이 중단되어도 데이터가 손상되는 것을 막아 줍니다.

상세 정보

작성자의 원본 설명

Thread-safe data persistence in Swift using actors — in-memory cache with file-backed storage, eliminating data races by design. Use when persisting data in Swift and a data race or thread-safety problem needs designing out.

repo: affaan-m/ECC

인기도

GitHub 스타
280k
순위
#249
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬