This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: swift-6-actor-isolation-data-race-safety-standard

Swift 6 Actor Isolation and Compile-Time Data-Race Safety Standard

Enforces complete compile-time concurrency checking and actor isolation guarantees under Swift 6 mode. Eliminates mutable reference escapes, unsafe global state, and non-sendable cross-isolation crossings to eradicate data races, deadlocks, and corrupted multithreaded application states.

Prohibited Anti-Pattern: Bypassing Strict Concurrency via Unsafe Unchecked Conformance and Shared Mutable Reference Passing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Actor Isolation and Compile-Time Data-Race Safety Standard - Enforces complete compile-time concurrency checking and actor isolation guarantees under Swift 6 mode. Eliminates mutable reference escapes, unsafe global state, and non-sendable cross-isolation crossings to eradicate data races, deadlocks, and corrupted multithreaded application states.
globs: **/*.swift, Package.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift-6-actor-isolation-data-race-safety-standard"
---

# Swift 6 Actor Isolation and Compile-Time Data-Race Safety Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bypassing Strict Concurrency via Unsafe Unchecked Conformance and Shared Mutable Reference Passing

## System Constraints
You are a Principal Software Architect enforcing the Swift 6 Actor Isolation and Compile-Time Data-Race Safety Standard. Mandate strict actor isolation, immutable data transfer across isolation boundaries, and explicit structured concurrency. Disallow unchecked sendability workarounds, raw locks without isolated encapsulation, and shared mutable state across threads.

## Strict Guidelines
- Engineers MUST ALWAYS enable complete concurrency checking (-strict-concurrency=complete) and target the Swift 6 language mode.
- Engineers MUST NOT mark reference types as '@unchecked Sendable' simply to silence compiler diagnostics without an externally validated synchronization primitive (such as an OSAllocatedUnfairLock or Mutex).
- Code MUST explicitly isolate state mutations to dedicated 'actor' types or global actors (e.g., '@MainActor' for UI mutations and UI-bound coordinators).
- Services MUST pass value types ('struct', 'enum') or provably immutable '@Sendable' types across actor boundaries and asynchronous tasks.
- Components NEVER capture mutable local variables inside escaping '@Sendable' closures or unstructured 'Task.init' blocks.

## Bad vs Good Implementations
### Background Data Fetching and State Mutation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring 'SessionCache' as '@unchecked Sendable' bypasses Swift 6 compile-time race checks without actual synchronization. Mutating the underlying dictionary across concurrent Dispatch queues produces data races and unpredictable crashes.
```swift
// ANTI-PATTERN: Mutable reference type passed across thread boundaries, mutating state without isolation
final class SessionCache: @unchecked Sendable {
    private var cache: [String: Data] = [:]

    func update(token: String, payload: Data) {
        // Unsynchronized concurrent mutation: causes memory corruption and SIGSEGV
        cache[token] = payload
    }
}

class DataManager {
    let cache = SessionCache()

    func processData(token: String, fetcher: @escaping () -> Data) {
        DispatchQueue.global().async {
            let data = fetcher()
            self.cache.update(token: token, payload: data)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulating cache mutations within a Swift 'actor' guarantees mutual exclusion at compile time. Data cross-isolation occurs using '@Sendable' closures and asynchronous calls ('await'), enforcing safety in Swift 6 without thread locks or unmanaged race conditions.
```swift
// PRODUCTION STANDARD: Swift 6 Actor Isolation with Structured Concurrency and Value Semantics
actor SessionCache {
    private var cache: [String: Data] = [:]

    func update(token: String, payload: Data) {
        cache[token] = payload
    }

    func payload(for token: String) -> Data? {
        cache[token]
    }
}

actor DataManager {
    private let cache: SessionCache

    init(cache: SessionCache) {
        self.cache = cache
    }

    func processData(token: String, fetcher: @Sendable () async throws -> Data) async throws {
        let data = try await fetcher()
        await cache.update(token: token, payload: data)
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Swift 6 Actor Isolation and Compile-Time Data-Race Safety Standard

Swift 6 Actor Isolation and Compile-Time Data-Race Safety Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces complete compile-time concurrency checking and actor isolation guarantees under Swift 6 mode. Eliminates mutable reference escapes, unsafe global state, and non-sendable cross-isolation crossings to eradicate data races, deadlocks, and corrupted multithreaded application states. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Bypassing Strict Concurrency via Unsafe Unchecked Conformance and Shared Mutable Reference Passing Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftBypassing Strict Concurrency via Unsafe Unchecked Conformance and Shared Mutable Reference PassingCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS enable complete concurrency checking (-strict-concurrency=complete) and target the Swift 6 language mode.

Engineers MUST ALWAYS enable complete concurrency checking (-strict-concurrency=complete) and target the Swift 6 language mode.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT mark reference types as '@unchecked Sendable' simply to silence compiler diagnostics without an externally validated synchronization primitive (such as an OSAllocatedUnfairLock or Mutex).

Engineers MUST NOT mark reference types as '@unchecked Sendable' simply to silence compiler diagnostics without an externally validated synchronization primitive (such as an OSAllocatedUnfairLock or Mutex).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST explicitly isolate state mutations to dedicated 'actor' types or global actors (e.g., '@MainActor' for UI mutations and UI-bound coordinators).

Code MUST explicitly isolate state mutations to dedicated 'actor' types or global actors (e.g., '@MainActor' for UI mutations and UI-bound coordinators).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST pass value types ('struct', 'enum') or provably immutable '@Sendable' types across actor boundaries and asynchronous tasks.

Services MUST pass value types ('struct', 'enum') or provably immutable '@Sendable' types across actor boundaries and asynchronous tasks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER capture mutable local variables inside escaping '@Sendable' closures or unstructured 'Task.init' blocks.

Components NEVER capture mutable local variables inside escaping '@Sendable' closures or unstructured 'Task.init' blocks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Swift 6 Actor Isolation and Compile-Time Data-Race Safety Standard critical for AI coding assistants?

Enforces complete compile-time concurrency checking and actor isolation guarantees under Swift 6 mode. Eliminates mutable reference escapes, unsafe global state, and non-sendable cross-isolation crossings to eradicate data races, deadlocks, and corrupted multithreaded application states. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Bypassing Strict Concurrency via Unsafe Unchecked Conformance and Shared Mutable Reference Passing) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Swift