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

swift-concurrency-6-2

하는 일

이 도구는 Swift 6.2의 새로운 동시성 기능을 사용하도록 돕습니다. 여러 부분의 프로그램이 같은 정보에 동시에 접근할 때 생기는 흔한 오류를 막아 코드를 더 안전하게 만듭니다. 특히 백그라운드 작업에 유용합니다.

사용하는 경우

  • ✓Swift 코드를 6.2 버전으로 옮길 때.
  • ✓컴파일러가 ‘데이터 레이스’ 오류(안전하지 않은 데이터 접근)를 보고할 때.
  • ✓메인 프로그램을 멈추지 않고 백그라운드에서 실행해야 하는 작업을 정리할 때.

스킬 링크

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

AI에게 요청하는 예시

“Swift 6.2에서 시간이 오래 걸리는 작업을 안전하게 백그라운드에서 실행하려면 어떻게 해야 할까요?”

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

작동 방식

Swift 6.2는 `@concurrent`를 명시적으로 쓰지 않는 한, 코드가 호출된 곳에서 계속 실행되도록 기본 동작을 바꿉니다. 이렇게 하면 여러 코드 부분이 실수로 같은 데이터를 동시에 바꾸는 것을 막습니다.

기술 내용 (원본 SKILL.md)

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

Swift 6.2 Approachable Concurrency

Patterns for adopting Swift 6.2's concurrency model where code runs single-threaded by default and concurrency is introduced explicitly. Eliminates common data-race errors without sacrificing performance.

When to Activate

  • Migrating Swift 5.x or 6.0/6.1 projects to Swift 6.2
  • Resolving data-race safety compiler errors
  • Designing MainActor-based app architecture
  • Offloading CPU-intensive work to background threads
  • Implementing protocol conformances on MainActor-isolated types
  • Enabling Approachable Concurrency build settings in Xcode 26

Core Problem: Implicit Background Offloading

In Swift 6.1 and earlier, async functions could be implicitly offloaded to background threads, causing data-race errors even in seemingly safe code:

// Swift 6.1: ERROR
@MainActor
final class StickerModel {
    let photoProcessor = PhotoProcessor()

    func extractSticker(_ item: PhotosPickerItem) async throws -> Sticker? {
        guard let data = try await item.loadTransferable(type: Data.self) else { return nil }

        // Error: Sending 'self.photoProcessor' risks causing data races
        return await photoProcessor.extractSticker(data: data, with: item.itemIdentifier)
    }
}

Swift 6.2 fixes this: async functions stay on the calling actor by default.

// Swift 6.2: OK — async stays on MainActor, no data race
@MainActor
final class StickerModel {
    let photoProcessor = PhotoProcessor()

    func extractSticker(_ item: PhotosPickerItem) async throws -> Sticker? {
        guard let data = try await item.loadTransferable(type: Data.self) else { return nil }
        return await photoProcessor.extractSticker(data: data, with: item.itemIdentifier)
    }
}

Core Pattern — Isolated Conformances

MainActor types can now conform to non-isolated protocols safely:

protocol Exportable {
    func export()
}

// Swift 6.1: ERROR — crosses into main actor-isolated code
// Swift 6.2: OK with isolated conformance
extension StickerModel: @MainActor Exportable {
    func export() {
        photoProcessor.exportAsPNG()
    }
}

The compiler ensures the conformance is only used on the main actor:

// OK — ImageExporter is also @MainActor
@MainActor
struct ImageExporter {
    var items: [any Exportable]

    mutating func add(_ item: StickerModel) {
        items.append(item)  // Safe: same actor isolation
    }
}

// ERROR — nonisolated context can't use MainActor conformance
nonisolated struct ImageExporter {
    var items: [any Exportable]

    mutating func add(_ item: StickerModel) {
        items.append(item)  // Error: Main actor-isolated conformance cannot be used here
    }
}

Core Pattern — Global and Static Variables

Protect global/static state with MainActor:

// Swift 6.1: ERROR — non-Sendable type may have shared mutable state
final class StickerLibrary {
    static let shared: StickerLibrary = .init()  // Error
}

// Fix: Annotate with @MainActor
@MainActor
final class StickerLibrary {
    static let shared: StickerLibrary = .init()  // OK
}

MainActor Default Inference Mode

Swift 6.2 introduces a mode where MainActor is inferred by default — no manual annotations needed:

// With MainActor default inference enabled:
final class StickerLibrary {
    static let shared: StickerLibrary = .init()  // Implicitly @MainActor
}

final class StickerModel {
    let photoProcessor: PhotoProcessor
    var selection: [PhotosPickerItem]  // Implicitly @MainActor
}

extension StickerModel: Exportable {  // Implicitly @MainActor conformance
    func export() {
        photoProcessor.exportAsPNG()
    }
}

This mode is opt-in and recommended for apps, scripts, and other executable targets.

Core Pattern — @concurrent for Background Work

When you need actual parallelism, explicitly offload with @concurrent:

Important: This example requires Approachable Concurrency build settings — SE-0466 (MainActor default isolation) and SE-0461 (NonisolatedNonsendingByDefault). With these enabled, extractSticker stays on the caller's actor, making mutable state access safe. Without these settings, this code has a data race — the compiler will flag it.

nonisolated final class PhotoProcessor {
    private var cachedStickers: [String: Sticker] = [:]

    func extractSticker(data: Data, with id: String) async -> Sticker {
        if let sticker = cachedStickers[id] {
            return sticker

…
자주 묻는 질문

‘데이터 레이스’란 무엇인가요?

프로그램의 두 개 이상의 부분이 같은 데이터를 동시에 읽고 쓸 때 발생하는 오류입니다. 예측할 수 없는 결과나 충돌을 일으킬 수 있습니다.

‘기본적으로 단일 스레드’란 무엇을 뜻하나요?

기본적으로 코드가 대기열처럼 하나의 실행 스레드에서 돌아간다는 뜻입니다. 한 번에 하나만 일어나므로 ‘데이터 레이스’ 오류를 피하기 쉽습니다.

`@concurrent`란 무엇인가요?

특정 함수를 메인 흐름을 방해하지 않도록 다른 스레드에서 백그라운드로 실행하라고 Swift에 알리는 특별한 지시어입니다.

상세 정보

작성자의 원본 설명

Swift 6.2 Approachable Concurrency — single-threaded by default, @concurrent for explicit background offloading, isolated conformances for main actor types. Use when adopting Swift 6.2 concurrency — offloading with @concurrent or resolving main-actor isolation.

repo: affaan-m/ECC

인기도

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

이 스킬이 유용한가요?

0

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

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬