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

Swift 6 Complete Concurrency & Sendable Actor Isolation Standard

Enforces complete compile-time data-race safety across iOS/macOS runtime environments in Swift 6 mode. Mandates strict conformance to Sendable across actor and task execution domains, eliminating unsynchronized mutable state across concurrent threads.

Prohibited Anti-Pattern: Bypassing Sendable Checks via @unchecked Sendable or Mutating Mutable Reference Types Across Task Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Complete Concurrency & Sendable Actor Isolation Standard - Enforces complete compile-time data-race safety across iOS/macOS runtime environments in Swift 6 mode. Mandates strict conformance to Sendable across actor and task execution domains, eliminating unsynchronized mutable state across concurrent threads.
globs: **/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift-6-complete-concurrency-actor-isolation"
---

# Swift 6 Complete Concurrency & Sendable Actor Isolation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bypassing Sendable Checks via @unchecked Sendable or Mutating Mutable Reference Types Across Task Boundaries

## System Constraints
You are a Principal Mobile Architect enforcing the Swift 6 Complete Concurrency & Sendable Actor Isolation Standard. Under Swift 6, data-race freedom is statically verified at compile time. Never allow unisolated mutable reference types to escape across actor or Task boundaries. Forbid arbitrary usage of `@unchecked Sendable` without exhaustive thread-safe synchronization (such as os_unfair_lock or Mutex). Always preserve MainActor UI bindings and prioritize structured concurrency (TaskGroup, async let) over unstructured detached tasks.

## Strict Guidelines
- Engineers MUST ALWAYS compile with Complete Concurrency Checking enabled (`-strict-concurrency=complete` or Swift 6 language mode) and resolve all concurrency diagnostics without suppressions.
- Engineers MUST NOT pass non-Sendable mutable class instances across actor isolation boundaries, Task initializers, or TaskGroup iterations.
- Code SHOULD prefer immutable value types (`struct`, `enum`) for cross-boundary data transfer objects (DTOs) and state snapshots to gain implicit Sendable conformance.
- Services MUST isolate shared mutable state within an `actor` or synchronize fields explicitly using the synchronization primitives like `Synchronization.Mutex`.
- Components NEVER bridge UI state mutations off the `@MainActor`; view models, UI coordinators, and UIKit/SwiftUI bindings must explicitly declare `@MainActor` isolation.
- Engineers MUST NOT apply `@unchecked Sendable` as a workaround to silence compiler warnings; any usage requires architectural justification and non-reentrant low-level lock synchronization.

## Bad vs Good Implementations
### State Isolation and Cross-Task Boundary Transfer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: SessionManager is a non-Sendable reference type. Passing it across actor boundaries into an unstructured Task creates an undetected data race on `activeToken`, crashing or corrupting memory at runtime.
```swift
import Foundation

// Non-Sendable reference type holding mutable state
final class SessionManager {
    var activeToken: String?
}

actor NetworkService {
    func authenticate(session: SessionManager) async {
        // Race hazard: SessionManager captured and mutated across concurrent contexts
        Task.detached {
            session.activeToken = "token_" + UUID().uuidString
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: NetworkService encapsulates mutable state within actor isolation. Data passed across execution boundaries uses the immutable, Sendable-conforming struct `SessionCredentials`, ensuring zero race conditions.
```swift
import Foundation
import Synchronization

// Immutable value type implicitly Sendable
struct SessionCredentials: Sendable, Equatable {
    let token: String
    let expiresAt: Date
}

actor NetworkService {
    private var currentSession: SessionCredentials?

    func authenticate() async -> SessionCredentials {
        let newCredentials = SessionCredentials(
            token: "token_" + UUID().uuidString,
            expiresAt: Date().addingTimeInterval(3600)
        )
        self.currentSession = newCredentials
        return newCredentials
    }
}
```

### UI State Mutation Isolated to MainActor

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: ProfileViewModel updates @Published property `username` from a non-isolated Task execution context, violating Swift 6 UI thread-affinity rules and causing main-thread assertion failures.
```swift
import SwiftUI

class ProfileViewModel: ObservableObject {
    @Published var username: String = ""

    func fetchProfile() {
        Task {
            let name = await Task.detached { "alice_dev" }.value
            // Mutation occurs on arbitrary cooperative thread pool thread
            self.username = name
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The entire class is isolated to `@MainActor`, ensuring all UI-bound updates occur on the main thread, while background calculation is safely isolated inside a nonisolated static method returning a Sendable type.
```swift
import SwiftUI

@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var username: String = ""

    func fetchProfile() async {
        let name = await Self.retrieveRemoteUsername()
        // Mutation guaranteed to execute on MainActor
        self.username = name
    }

    private nonisolated static func retrieveRemoteUsername() async -> String {
        return "alice_dev"
    }
}
```

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 Complete Concurrency & Sendable Actor Isolation Standard

Swift 6 Complete Concurrency & Sendable Actor Isolation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces complete compile-time data-race safety across iOS/macOS runtime environments in Swift 6 mode. Mandates strict conformance to Sendable across actor and task execution domains, eliminating unsynchronized mutable state across concurrent threads. 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 Sendable Checks via @unchecked Sendable or Mutating Mutable Reference Types Across Task Boundaries 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 Sendable Checks via @unchecked Sendable or Mutating Mutable Reference Types Across Task BoundariesCritical
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 compile with Complete Concurrency Checking enabled (`-strict-concurrency=complete` or Swift 6 language mode) and resolve all concurrency diagnostics without suppressions.

Engineers MUST ALWAYS compile with Complete Concurrency Checking enabled (`-strict-concurrency=complete` or Swift 6 language mode) and resolve all concurrency diagnostics without suppressions.

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 pass non-Sendable mutable class instances across actor isolation boundaries, Task initializers, or TaskGroup iterations.

Engineers MUST NOT pass non-Sendable mutable class instances across actor isolation boundaries, Task initializers, or TaskGroup iterations.

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 SHOULD prefer immutable value types (`struct`, `enum`) for cross-boundary data transfer objects (DTOs) and state snapshots to gain implicit Sendable conformance.

Code SHOULD prefer immutable value types (`struct`, `enum`) for cross-boundary data transfer objects (DTOs) and state snapshots to gain implicit Sendable conformance.

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 isolate shared mutable state within an `actor` or synchronize fields explicitly using the synchronization primitives like `Synchronization.Mutex`.

Services MUST isolate shared mutable state within an `actor` or synchronize fields explicitly using the synchronization primitives like `Synchronization.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.
5

Components NEVER bridge UI state mutations off the `@MainActor`

Components NEVER bridge UI state mutations off the `@MainActor`; view models, UI coordinators, and UIKit/SwiftUI bindings must explicitly declare `@MainActor` isolation.

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.
6

Engineers MUST NOT apply `@unchecked Sendable` as a workaround to silence compiler warnings

Engineers MUST NOT apply `@unchecked Sendable` as a workaround to silence compiler warnings; any usage requires architectural justification and non-reentrant low-level lock synchronization.

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 Complete Concurrency & Sendable Actor Isolation Standard critical for AI coding assistants?

Enforces complete compile-time data-race safety across iOS/macOS runtime environments in Swift 6 mode. Mandates strict conformance to Sendable across actor and task execution domains, eliminating unsynchronized mutable state across concurrent threads. 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 Sendable Checks via @unchecked Sendable or Mutating Mutable Reference Types Across Task Boundaries) 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