This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-swift-arc-memory-interop-guardrail

Kotlin Multiplatform Swift-ARC Native Memory Boundary Interop Standard

Establishes strict thread-confinement and reference lifecycle invariants across the Kotlin Native GC and Swift ARC bridge. Prevents silent cyclic reference memory leaks and retain cycles caused by cross-runtime listener delegation and closure capturing. Mandates weak reference wrappers, explicit cancellation tokens, and structural bridge teardown routines on iOS targets.

Prohibited Anti-Pattern: Cross-Runtime Retain Cycles Between Swift ARC and Kotlin Native Tracing Collector

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift-ARC Native Memory Boundary Interop Standard - Establishes strict thread-confinement and reference lifecycle invariants across the Kotlin Native GC and Swift ARC bridge. Prevents silent cyclic reference memory leaks and retain cycles caused by cross-runtime listener delegation and closure capturing. Mandates weak reference wrappers, explicit cancellation tokens, and structural bridge teardown routines on iOS targets.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-arc-memory-interop-guardrail"
---

# Kotlin Multiplatform Swift-ARC Native Memory Boundary Interop Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Runtime Retain Cycles Between Swift ARC and Kotlin Native Tracing Collector

## System Constraints
You are a Principal Mobile Architect enforcing cross-platform memory invariants between Kotlin Multiplatform and Swift ARC. Your mandate is to prevent silent bridge memory leaks, uncollected GC roots, and cross-runtime retain cycles. Every cross-language delegation must adhere to explicit thread-confinement rules, unowned/weak closure capturing, and deterministic lifecycle unwinding.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Swift delegate implementations passed to Kotlin Native in a weak or unowned reference adapter.
- Engineers MUST NOT allow Kotlin Native objects holding Swift closures to be referenced by those same Swift closures, forming cross-runtime cycles.
- Engineers MUST ALWAYS implement an explicit `close()` or `detach()` lifecycle method on Kotlin observers/presenters exposed to Objective-C/Swift.
- Code MUST explicitly cancel and nullify active Kotlin `Job` or `CoroutineScope` instances when an iOS UIViewController or SwiftUI view disappears.
- Engineers MUST NEVER capture strong references to Kotlin StateFlow wrappers inside long-lived Swift async tasks or Combine pipelines without `[weak self]` guards.
- Bridged callbacks MUST be dispatched on the Main thread unless explicitly isolated to an off-thread Kotlin background worker using thread-safe primitives.
- Engineers MUST audit Kotlin Native exported interfaces with Xcode Instruments (Leaks / Allocations) after adding persistent event subscriptions.

## Bad vs Good Implementations
### Swift Listener Subscription to Kotlin Multiplatform ViewModel

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native holds an Objective-C strong reference to the callback closure, which captures 'self' strongly. Since 'self' (ProfileViewController) also owns 'viewModel', neither the Kotlin GC nor Swift ARC can reclaim these instances, causing a permanent memory leak.
```swift
// BAD: Strong cyclic retention across Swift ARC and Kotlin Native GC
class ProfileViewController: UIViewController {
    private let viewModel = ProfileViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Strongly captures self into Kotlin runtime listener list
        // Kotlin GC holds Swift closure -> Swift closure retains self -> self retains viewModel
        viewModel.observeState { state in
            self.updateUI(state: state)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The closure captures `[weak self]` to avoid ARC retention. Storing a DisposableHandle allows the iOS lifecycle to deterministically remove the listener from the Kotlin Native root graph, severing the bridge cycle upon dismissal.
```swift
// GOOD: Weak capturing with explicit lifecycle detachment via DisposableHandle
class ProfileViewController: UIViewController {
    private let viewModel = ProfileViewModel()
    private var observationHandle: DisposableHandle?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        observationHandle = viewModel.observeState { [weak self] state in
            guard let self = self else { return }
            self.updateUI(state: state)
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if isMovingFromParent || isBeingDismissed {
            observationHandle?.dispose()
            observationHandle = nil
        }
    }
}
```

### Kotlin Native Flow Adapter for Swift Observation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The launched coroutine runs as long as the ViewModelScope is alive. Since it retains the Objective-C block provided by Swift, ARC cannot free any resources captured within the block, even if the native iOS UI component is discarded.
```kotlin
// BAD: Shared flow collector leaks Swift block reference indefinitely
class ProfileViewModel : ViewModel() {
    private val _uiState = MutableStateFlow<UiState>(UiState.Initial)
    val uiState: StateFlow<UiState> = _uiState.asStateFlow()
    
    fun observeState(onUpdate: (UiState) -> Unit) {
        // Launches on ViewModelScope without returning cancellation handle
        // Creates an unmanaged GC root retaining the Swift-provided lambda forever
        viewModelScope.launch {
            _uiState.collect { state ->
                onUpdate(state)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Returns a DisposableHandle directly to the Swift caller. This forces structured cleanup across the FFI boundary and ensures the coroutine job is cancelled, freeing the pinned Swift closure block.
```kotlin
// GOOD: Returns a DisposableHandle for deterministic cross-runtime cleanup
class ProfileViewModel : ViewModel() {
    private val _uiState = MutableStateFlow<UiState>(UiState.Initial)
    val uiState: StateFlow<UiState> = _uiState.asStateFlow()
    
    fun observeState(onUpdate: (UiState) -> Unit): DisposableHandle {
        val job = viewModelScope.launch(Dispatchers.Main.immediate) {
            _uiState.collect { state ->
                onUpdate(state)
            }
        }
        return DisposableHandle { job.cancel() }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform Swift-ARC Native Memory Boundary Interop Standard

Kotlin Multiplatform Swift-ARC Native Memory Boundary Interop Standard defines an industrial-grade behavioral standard for mobile engineering. Establishes strict thread-confinement and reference lifecycle invariants across the Kotlin Native GC and Swift ARC bridge. Prevents silent cyclic reference memory leaks and retain cycles caused by cross-runtime listener delegation and closure capturing. Mandates weak reference wrappers, explicit cancellation tokens, and structural bridge teardown routines on iOS targets. 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: Cross-Runtime Retain Cycles Between Swift ARC and Kotlin Native Tracing Collector 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 DriftCross-Runtime Retain Cycles Between Swift ARC and Kotlin Native Tracing CollectorCritical
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 wrap Swift delegate implementations passed to Kotlin Native in a weak or unowned reference adapter.

Engineers MUST ALWAYS wrap Swift delegate implementations passed to Kotlin Native in a weak or unowned reference adapter.

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 allow Kotlin Native objects holding Swift closures to be referenced by those same Swift closures, forming cross-runtime cycles.

Engineers MUST NOT allow Kotlin Native objects holding Swift closures to be referenced by those same Swift closures, forming cross-runtime cycles.

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 ALWAYS implement an explicit `close()` or `detach()` lifecycle method on Kotlin observers/presenters exposed to Objective-C/Swift.

Engineers MUST ALWAYS implement an explicit `close()` or `detach()` lifecycle method on Kotlin observers/presenters exposed to Objective-C/Swift.

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

Code MUST explicitly cancel and nullify active Kotlin `Job` or `CoroutineScope` instances when an iOS UIViewController or SwiftUI view disappears.

Code MUST explicitly cancel and nullify active Kotlin `Job` or `CoroutineScope` instances when an iOS UIViewController or SwiftUI view disappears.

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 NEVER capture strong references to Kotlin StateFlow wrappers inside long-lived Swift async tasks or Combine pipelines without `[weak self]` guards.

Engineers MUST NEVER capture strong references to Kotlin StateFlow wrappers inside long-lived Swift async tasks or Combine pipelines without `[weak self]` guards.

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

Bridged callbacks MUST be dispatched on the Main thread unless explicitly isolated to an off-thread Kotlin background worker using thread-safe primitives.

Bridged callbacks MUST be dispatched on the Main thread unless explicitly isolated to an off-thread Kotlin background worker using thread-safe primitives.

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

Engineers MUST audit Kotlin Native exported interfaces with Xcode Instruments (Leaks / Allocations) after adding persistent event subscriptions.

Engineers MUST audit Kotlin Native exported interfaces with Xcode Instruments (Leaks / Allocations) after adding persistent event subscriptions.

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 Kotlin Multiplatform Swift-ARC Native Memory Boundary Interop Standard critical for AI coding assistants?

Establishes strict thread-confinement and reference lifecycle invariants across the Kotlin Native GC and Swift ARC bridge. Prevents silent cyclic reference memory leaks and retain cycles caused by cross-runtime listener delegation and closure capturing. Mandates weak reference wrappers, explicit cancellation tokens, and structural bridge teardown routines on iOS targets. 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 (Cross-Runtime Retain Cycles Between Swift ARC and Kotlin Native Tracing Collector) 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

Kotlin