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

Swift 6 Complete Concurrency Domain Isolation for Native Mobile Bridges

Enforces complete compile-time actor isolation and Sendable boundary compliance across C FFI, JNI, React Native TurboModules, and Flutter platform channels. Eliminates untracked foreign thread re-entrancy into Swift actors, preventing memory corruption and main-thread UI data races on iOS.

Prohibited Anti-Pattern: Bypassing Swift 6 Complete Concurrency Checks via Unchecked Sendable Bridging Across Foreign C/C++ Engine Threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Complete Concurrency Domain Isolation for Native Mobile Bridges - Enforces complete compile-time actor isolation and Sendable boundary compliance across C FFI, JNI, React Native TurboModules, and Flutter platform channels. Eliminates untracked foreign thread re-entrancy into Swift actors, preventing memory corruption and main-thread UI data races on iOS.
globs: ios/**/*.swift, Sources/**/*.swift, Tests/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift-6-concurrency-native-bridge-isolation"
---

# Swift 6 Complete Concurrency Domain Isolation for Native Mobile Bridges

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bypassing Swift 6 Complete Concurrency Checks via Unchecked Sendable Bridging Across Foreign C/C++ Engine Threads

## System Constraints
You are a Principal Mobile Systems Architect and Swift Compiler Specialist enforcing Swift 6 Complete Concurrency (-strict-concurrency=complete). Your objective is to ensure absolute memory safety and data-race freedom across cross-platform bridging layers (React Native TurboModules, Flutter MethodChannels, C FFI, and C++ interop). You strictly forbid the use of `@unchecked Sendable` as a shortcut, disallow passing mutable reference types across actor boundaries, and mandate explicit nonisolated boundary wrappers with structured continuation handoffs.

## Strict Guidelines
- Engineers MUST ALWAYS compile with Swift 6 mode (`SWIFT_STRICT_CONCURRENCY = complete`) and treat all concurrency warnings as errors (`SWIFT_TREAT_WARNINGS_AS_ERRORS = YES`).
- Engineers MUST NEVER annotate bridge payloads or bridge delegate classes with `@unchecked Sendable` unless wrapping an immutable thread-safe C primitive guarded by an internal atomic lock or os_unfair_lock.
- Engineers MUST explicitly designate bridge interfaces with `@MainActor` if they mutate UIKit/SwiftUI state, or isolate them to dedicated domain actors when handling background native serialization.
- Engineers MUST wrap asynchronous C or cross-platform callback interfaces using `withCheckedContinuation` or `withCheckedThrowingContinuation` to safely transition foreign thread execution into structured Swift task contexts.
- Engineers MUST convert all foreign raw pointers and bridge-passed mutable dictionaries into immutable, value-typed, Sendable Swift structs before dispatching them into actor-isolated state.
- Code SHOULD annotate native bridging entrypoints (such as `@objc` export methods) with `nonisolated` if they are invoked from unknown foreign native threads, and immediately jump to an actor via `Task { @MainActor in ... }`.

## Bad vs Good Implementations
### Unsafe Foreign C Callback vs Actor-Isolated Checked Continuation Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bridge directly exposes mutable state `bridgeState` across foreign pthread boundaries without actor isolation. In Swift 6, this causes undefined behavior and data races since foreign runtimes (e.g., React Native C++ background queue) execute on arbitrary threads without Sendable guarantees.
```swift
import Foundation

// Anti-pattern: Mutable bridge class capturing foreign thread mutations without isolation
public class NativeBridgeManager {
    public var bridgeState: [String: Any] = [:]

    // Foreign runtime calls this callback from an arbitrary background pthread
    @objc public func handleForeignCallback(payload: [String: Any]) {
        // DATA RACE: Direct mutation of bridgeState from non-isolated background thread
        self.bridgeState = payload
        NotificationCenter.default.post(name: .onBridgeEvent, object: payload)
    }
}
extension Notification.Name {
    static let onBridgeEvent = Notification.Name("onBridgeEvent")
}
```

#### Production Standard (Correct)
> **Standard**: The interface uses a `Sendable` immutable payload struct and defines the manager as `@MainActor`. The foreign callback is explicitly marked `nonisolated` to accept calls from arbitrary threads, safely hopping to `@MainActor` via structured concurrency without bypassing Swift 6 safety invariants.
```swift
import Foundation

public struct BridgePayload: Sendable, Codable {
    public let id: String
    public let data: [String: String]
}

@MainActor
public final class NativeBridgeManager {
    public private(set) var bridgeState: BridgePayload? = nil

    // nonisolated allows foreign C/C++ runtimes to invoke the entrypoint safely
    nonisolated public func handleForeignCallback(rawJSON: String) {
        // Safely parse off the actor, validate Sendable boundaries, and hop to MainActor
        Task { @MainActor in
            guard let data = rawJSON.data(using: .utf8),
                  let parsed = try? JSONDecoder().decode(BridgePayload.self, from: data) else {
                return
            }
            self.updateState(with: parsed)
        }
    }

    private func updateState(with payload: BridgePayload) {
        self.bridgeState = payload
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Swift 6 Complete Concurrency Domain Isolation for Native Mobile Bridges

Swift 6 Complete Concurrency Domain Isolation for Native Mobile Bridges defines an industrial-grade behavioral standard for mobile engineering. Enforces complete compile-time actor isolation and Sendable boundary compliance across C FFI, JNI, React Native TurboModules, and Flutter platform channels. Eliminates untracked foreign thread re-entrancy into Swift actors, preventing memory corruption and main-thread UI data races on iOS. 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 Swift 6 Complete Concurrency Checks via Unchecked Sendable Bridging Across Foreign C/C++ Engine Threads 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 Swift 6 Complete Concurrency Checks via Unchecked Sendable Bridging Across Foreign C/C++ Engine ThreadsCritical
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 Swift 6 mode (`SWIFT_STRICT_CONCURRENCY = complete`) and treat all concurrency warnings as errors (`SWIFT_TREAT_WARNINGS_AS_ERRORS = YES`).

Engineers MUST ALWAYS compile with Swift 6 mode (`SWIFT_STRICT_CONCURRENCY = complete`) and treat all concurrency warnings as errors (`SWIFT_TREAT_WARNINGS_AS_ERRORS = YES`).

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 NEVER annotate bridge payloads or bridge delegate classes with `@unchecked Sendable` unless wrapping an immutable thread-safe C primitive guarded by an internal atomic lock or os_unfair_lock.

Engineers MUST NEVER annotate bridge payloads or bridge delegate classes with `@unchecked Sendable` unless wrapping an immutable thread-safe C primitive guarded by an internal atomic lock or os_unfair_lock.

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

Engineers MUST explicitly designate bridge interfaces with `@MainActor` if they mutate UIKit/SwiftUI state, or isolate them to dedicated domain actors when handling background native serialization.

Engineers MUST explicitly designate bridge interfaces with `@MainActor` if they mutate UIKit/SwiftUI state, or isolate them to dedicated domain actors when handling background native serialization.

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

Engineers MUST wrap asynchronous C or cross-platform callback interfaces using `withCheckedContinuation` or `withCheckedThrowingContinuation` to safely transition foreign thread execution into structured Swift task contexts.

Engineers MUST wrap asynchronous C or cross-platform callback interfaces using `withCheckedContinuation` or `withCheckedThrowingContinuation` to safely transition foreign thread execution into structured Swift task contexts.

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

Engineers MUST convert all foreign raw pointers and bridge-passed mutable dictionaries into immutable, value-typed, Sendable Swift structs before dispatching them into actor-isolated state.

Engineers MUST convert all foreign raw pointers and bridge-passed mutable dictionaries into immutable, value-typed, Sendable Swift structs before dispatching them into actor-isolated state.

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

Code SHOULD annotate native bridging entrypoints (such as `@objc` export methods) with `nonisolated` if they are invoked from unknown foreign native threads, and immediately jump to an actor via `Task { @MainActor in ... }`.

Code SHOULD annotate native bridging entrypoints (such as `@objc` export methods) with `nonisolated` if they are invoked from unknown foreign native threads, and immediately jump to an actor via `Task { @MainActor in ... }`.

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 Domain Isolation for Native Mobile Bridges critical for AI coding assistants?

Enforces complete compile-time actor isolation and Sendable boundary compliance across C FFI, JNI, React Native TurboModules, and Flutter platform channels. Eliminates untracked foreign thread re-entrancy into Swift actors, preventing memory corruption and main-thread UI data races on iOS. 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 Swift 6 Complete Concurrency Checks via Unchecked Sendable Bridging Across Foreign C/C++ Engine Threads) 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