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

Kotlin Multiplatform Swift Interop ARC Strong Reference Cycle Guardrail

Enforces strict weak-reference and explicit lifecycle decoupling across the Kotlin/Native ARC boundary. Prevents cross-runtime heap retention cycles where Kotlin Native garbage collection and Apple Swift ARC fail to traverse foreign object graphs during bidirectional event delegation.

Prohibited Anti-Pattern: Cross-Runtime Zombie Heap Retention via Bidirectional Kotlin/Swift Strong Delegation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift Interop ARC Strong Reference Cycle Guardrail - Enforces strict weak-reference and explicit lifecycle decoupling across the Kotlin/Native ARC boundary. Prevents cross-runtime heap retention cycles where Kotlin Native garbage collection and Apple Swift ARC fail to traverse foreign object graphs during bidirectional event delegation.
globs: iosApp/**/*.swift, **/iosMain/**/*.kt, **/appleMain/**/*.kt, shared/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-arc-reference-cycle-guardrail"
---

# Kotlin Multiplatform Swift Interop ARC Strong Reference Cycle Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Runtime Zombie Heap Retention via Bidirectional Kotlin/Swift Strong Delegation

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Swift interoperability. You enforce non-leaking memory semantics across the Kotlin/Native and Swift ARC runtime boundary. Neither the Kotlin Native GC nor the Swift ARC collector can traverse reference graphs across the foreign function interface boundary. You mandate explicit weak references, non-capturing delegates, and deterministic teardown protocols for all cross-language bridges.

## Strict Guidelines
- Engineers MUST ALWAYS enforce weak capture semantics (`[weak self]`) within Swift closures passed into Kotlin Native APIs.
- Engineers MUST NOT assign a Swift class instance directly to a Kotlin strong property or delegate interface across the Obj-C export boundary without an intermediate weak wrapper.
- Kotlin-facing delegate protocols implemented in Swift MUST be declared as class-bound (`AnyObject`) and held via `weak` references on the Swift-side facade or wrapped via `kotlin.native.ref.WeakReference` in `iosMain`.
- Swift `UIViewController` and SwiftUI `View` instances MUST cancel and clear active KMP coroutine bridges, listeners, and observation tokens in `viewDidDisappear` or `onDisappear`.
- Architectures SHOULD replace bidirectional delegate patterns with Unidirectional Data Flow (UDF) via exported Kotlin `StateFlow` streams observed passively in Swift.
- Swift `deinit` MUST verify that all cross-runtime callbacks and bridge bindings have been set to nil, asserting zero remaining retain counts from exported Kotlin objects.

## Bad vs Good Implementations
### Bidirectional Delegation Across Kotlin/Swift Interop Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin ViewModel holds a strong reference to `ProfileViewDelegate` across the Objective-C/Swift interop boundary. Because `ProfileViewController` simultaneously holds the Kotlin `ProfileViewModel`, an uncollectible cross-runtime retain cycle is established. Neither Swift's ARC nor Kotlin's garbage collector can traverse foreign heaps, causing permanent heap leakage.
```swift
import UIKit
import SharedKit

// ANTI-PATTERN: Strong reference cycle across KMP/Swift runtime boundary.
// Kotlin ViewModel holds strong reference to Kotlin-facing delegate implemented by UIViewController.
// UIViewController holds strong reference to Kotlin ViewModel.
// Neither Swift ARC nor Kotlin GC can collect this cycle.
final class ProfileViewController: UIViewController, ProfileViewDelegate {
    private let viewModel: ProfileViewModel = ProfileViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Swift instance passes strong self to Kotlin, which stores it as a strong reference
        viewModel.delegate = self
        viewModel.loadProfile()
    }

    func onProfileLoaded(profile: ProfileDTO) {
        // UI update logic
    }
}
```

#### Production Standard (Correct)
> **Standard**: Replaces the bidirectional delegate anti-pattern with decoupled async state consumption. `[weak self]` prevents Swift retain cycles inside Task closures. The explicit `viewDidDisappear` teardown hook and `deinit` ensure that all Kotlin bridge coroutine scopes (`viewModel.clear()`) are actively severed, eliminating foreign runtime pinning.
```swift
import UIKit
import SharedKit

// PRODUCTION FIX: Unidirectional observation with explicit weak capture wrapper
// or explicit lifecycle unbinding to sever foreign ARC root pinning.
final class ProfileViewController: UIViewController {
    private let viewModel: ProfileViewModel = ProfileViewModel()
    private var profileTask: Task<Void, Never>?

    override func viewDidLoad() {
        super.viewDidLoad()
        bindViewModel()
    }

    private func bindViewModel() {
        // Consume Kotlin StateFlow or use explicit weak callback capture
        profileTask = Task { [weak self] in
            for await state in self?.viewModel.uiState ?? [] {
                guard let self = self else { return }
                self.render(state: state)
            }
        }
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if isMovingFromParent || isBeingDismissed {
            // Deterministically break any lingering bridge retainers
            profileTask?.cancel()
            profileTask = nil
            viewModel.clear()
        }
    }

    private func render(state: ProfileUiState) {
        // UI update logic safely executing without retain cycles
    }

    deinit {
        profileTask?.cancel()
        viewModel.clear()
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform Swift Interop ARC Strong Reference Cycle Guardrail

Kotlin Multiplatform Swift Interop ARC Strong Reference Cycle Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict weak-reference and explicit lifecycle decoupling across the Kotlin/Native ARC boundary. Prevents cross-runtime heap retention cycles where Kotlin Native garbage collection and Apple Swift ARC fail to traverse foreign object graphs during bidirectional event delegation. 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 Zombie Heap Retention via Bidirectional Kotlin/Swift Strong Delegation 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 Zombie Heap Retention via Bidirectional Kotlin/Swift Strong DelegationCritical
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 enforce weak capture semantics (`[weak self]`) within Swift closures passed into Kotlin Native APIs.

Engineers MUST ALWAYS enforce weak capture semantics (`[weak self]`) within Swift closures passed into Kotlin Native APIs.

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 assign a Swift class instance directly to a Kotlin strong property or delegate interface across the Obj-C export boundary without an intermediate weak wrapper.

Engineers MUST NOT assign a Swift class instance directly to a Kotlin strong property or delegate interface across the Obj-C export boundary without an intermediate weak wrapper.

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

Kotlin-facing delegate protocols implemented in Swift MUST be declared as class-bound (`AnyObject`) and held via `weak` references on the Swift-side facade or wrapped via `kotlin.native.ref.WeakReference` in `iosMain`.

Kotlin-facing delegate protocols implemented in Swift MUST be declared as class-bound (`AnyObject`) and held via `weak` references on the Swift-side facade or wrapped via `kotlin.native.ref.WeakReference` in `iosMain`.

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

Swift `UIViewController` and SwiftUI `View` instances MUST cancel and clear active KMP coroutine bridges, listeners, and observation tokens in `viewDidDisappear` or `onDisappear`.

Swift `UIViewController` and SwiftUI `View` instances MUST cancel and clear active KMP coroutine bridges, listeners, and observation tokens in `viewDidDisappear` or `onDisappear`.

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

Architectures SHOULD replace bidirectional delegate patterns with Unidirectional Data Flow (UDF) via exported Kotlin `StateFlow` streams observed passively in Swift.

Architectures SHOULD replace bidirectional delegate patterns with Unidirectional Data Flow (UDF) via exported Kotlin `StateFlow` streams observed passively in 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.
6

Swift `deinit` MUST verify that all cross-runtime callbacks and bridge bindings have been set to nil, asserting zero remaining retain counts from exported Kotlin objects.

Swift `deinit` MUST verify that all cross-runtime callbacks and bridge bindings have been set to nil, asserting zero remaining retain counts from exported Kotlin objects.

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 Interop ARC Strong Reference Cycle Guardrail critical for AI coding assistants?

Enforces strict weak-reference and explicit lifecycle decoupling across the Kotlin/Native ARC boundary. Prevents cross-runtime heap retention cycles where Kotlin Native garbage collection and Apple Swift ARC fail to traverse foreign object graphs during bidirectional event delegation. 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 Zombie Heap Retention via Bidirectional Kotlin/Swift Strong Delegation) 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