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

Kotlin Multiplatform Swift Interop Strong Reference Boundary Guardrail

Defines strict weak-reference semantics, scope termination lifecycles, and delegate decoupling across the Kotlin/Native ARC boundary to Apple Swift runtimes. Cross-language object graphs crossing this foreign function interface (FFI) lack unified cycle collectors, causing silent, non-reclaimable multi-megabyte retain cycles if strong references loop across runtimes.

Prohibited Anti-Pattern: Cross-Boundary Strong Retain Cycles Between Swift Delegates and Kotlin State Observers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift Interop Strong Reference Boundary Guardrail - Defines strict weak-reference semantics, scope termination lifecycles, and delegate decoupling across the Kotlin/Native ARC boundary to Apple Swift runtimes. Cross-language object graphs crossing this foreign function interface (FFI) lack unified cycle collectors, causing silent, non-reclaimable multi-megabyte retain cycles if strong references loop across runtimes.
globs: **/*.kt, **/*.swift, **/iosApp/**/*.swift, **/shared/src/iosMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-arc-reference-boundary"
---

# Kotlin Multiplatform Swift Interop Strong Reference Boundary Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Boundary Strong Retain Cycles Between Swift Delegates and Kotlin State Observers

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Apple Platforms runtime interop. Your mission is to eliminate cross-runtime retain cycles and native heap leaks between Kotlin/Native GC and Swift ARC. You mandate explicit weak references, scope cancellation lifecycles, and wrapper boundaries whenever bridging native platforms.

## Strict Guidelines
- Engineers MUST ALWAYS declare Swift-facing callback interfaces or delegates as weak inside Swift consuming classes or bridge via WeakReference/decoupled ID listeners.
- Engineers MUST NEVER capture strong references to Swift UI views, ViewControllers, or SwiftUI ViewModels inside Kotlin Native CoroutineScope closures or Flow collectors.
- Kotlin-exposed Presenters, ViewModels, or Controller instances MUST expose an explicit `detach()`, `clear()`, or `close()` lifecycle method that cancels inner `CoroutineScope` instances and nullifies bridge listeners.
- Swift code consuming Kotlin state via Flow or Combine bridges MUST explicitly invoke lifecycle cleanup (such as in `deinit` or `onDisappear`) to break the underlying Kotlin Native StableRef reference table.
- Kotlin/Native shared code MUST NEVER hold direct strong references to Swift closure delegates when passing them across asynchronous dispatch boundaries.

## Bad vs Good Implementations
### Swift UI / Kotlin ViewModel Delegate Retain Cycle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: A bidirectional strong cycle across the Swift ARC and Kotlin/Native runtime boundary cannot be detected by either garbage collector or reference counter, permanently leaking the entire UI hierarchy and Kotlin CoroutineScope.
```swift
// Swift UI Controller holding a strong Kotlin ViewModel while passing strong self
class ProfileViewController: UIViewController, ProfileUpdateListener {
    private let viewModel = ProfileViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        // CRITICAL BUG: Kotlin ViewModel stores this listener strongly in its internal list.
        // Swift owns ViewModel, Kotlin ViewModel holds strong reference back to Swift UI Controller.
        // Since Swift ARC and Kotlin/Native GC operate via separate root tables, neither releases.
        viewModel.setListener(listener: self)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Explicit boundary teardown in `viewDidDisappear` and `deinit` ensures that Kotlin clears its internal references and cancels background jobs, allowing ARC to deallocate the Swift controller and Kotlin Native GC to reclaim ViewModel memory.
```swift
// 1. Kotlin definition utilizes a weak reference wrapper or explicit detach lifecycle
// 2. Swift controller maintains ownership and breaks the cross-boundary reference on deinit
class ProfileViewController: UIViewController, ProfileUpdateListener {
    private let viewModel: ProfileViewModel
    
    init(viewModel: ProfileViewModel = ProfileViewModel()) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Pass weak-reference proxy or explicit lifecycle registration
        viewModel.attach(listener: self)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if isMovingFromParent || isBeingDismissed {
            viewModel.detach()
        }
    }

    deinit {
        // Guaranteed boundary clean-up to ensure StableRef dereferencing
        viewModel.detach()
    }
}
```

### Kotlin Native Flow Collector Lifecycle Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing an unmanaged Swift closure in a long-lived Kotlin property while running an uncancellable collection keeps Swift context captured in ARC root memory indefinitely.
```kotlin
// shared/src/iosMain/kotlin/ProfileViewModel.kt
class ProfileViewModel : ViewModel() {
    private var swiftCallback: ((UserProfile) -> Unit)? = null

    // Retains Swift closure indefinitely, preventing ARC collection of captured Swift context
    fun observeProfile(callback: (UserProfile) -> Unit) {
        this.swiftCallback = callback
        viewModelScope.launch {
            userRepository.profileFlow.collect { profile ->
                swiftCallback?.invoke(profile)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Provides an explicit `detach()` lifecycle contract that cancels active Coroutine collection and zeroes out the Swift callback reference, breaking cross-runtime object retention.
```kotlin
// shared/src/iosMain/kotlin/ProfileViewModel.kt
class ProfileViewModel : ViewModel() {
    private var observationJob: Job? = null
    private var swiftCallback: ((UserProfile) -> Unit)? = null

    fun observeProfile(callback: (UserProfile) -> Unit) {
        observationJob?.cancel()
        this.swiftCallback = callback
        observationJob = viewModelScope.launch {
            userRepository.profileFlow.collect { profile ->
                swiftCallback?.invoke(profile)
            }
        }
    }

    // Explicit cleanup hook invoked by Swift deinit or lifecycle observer
    fun detach() {
        observationJob?.cancel()
        observationJob = null
        swiftCallback = null
    }

    override fun onCleared() {
        detach()
        super.onCleared()
    }
}
```

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 Strong Reference Boundary Guardrail

Kotlin Multiplatform Swift Interop Strong Reference Boundary Guardrail defines an industrial-grade behavioral standard for mobile engineering. Defines strict weak-reference semantics, scope termination lifecycles, and delegate decoupling across the Kotlin/Native ARC boundary to Apple Swift runtimes. Cross-language object graphs crossing this foreign function interface (FFI) lack unified cycle collectors, causing silent, non-reclaimable multi-megabyte retain cycles if strong references loop across runtimes. 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-Boundary Strong Retain Cycles Between Swift Delegates and Kotlin State Observers 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-Boundary Strong Retain Cycles Between Swift Delegates and Kotlin State ObserversCritical
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 declare Swift-facing callback interfaces or delegates as weak inside Swift consuming classes or bridge via WeakReference/decoupled ID listeners.

Engineers MUST ALWAYS declare Swift-facing callback interfaces or delegates as weak inside Swift consuming classes or bridge via WeakReference/decoupled ID listeners.

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 capture strong references to Swift UI views, ViewControllers, or SwiftUI ViewModels inside Kotlin Native CoroutineScope closures or Flow collectors.

Engineers MUST NEVER capture strong references to Swift UI views, ViewControllers, or SwiftUI ViewModels inside Kotlin Native CoroutineScope closures or Flow collectors.

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-exposed Presenters, ViewModels, or Controller instances MUST expose an explicit `detach()`, `clear()`, or `close()` lifecycle method that cancels inner `CoroutineScope` instances and nullifies bridge listeners.

Kotlin-exposed Presenters, ViewModels, or Controller instances MUST expose an explicit `detach()`, `clear()`, or `close()` lifecycle method that cancels inner `CoroutineScope` instances and nullifies bridge listeners.

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 code consuming Kotlin state via Flow or Combine bridges MUST explicitly invoke lifecycle cleanup (such as in `deinit` or `onDisappear`) to break the underlying Kotlin Native StableRef reference table.

Swift code consuming Kotlin state via Flow or Combine bridges MUST explicitly invoke lifecycle cleanup (such as in `deinit` or `onDisappear`) to break the underlying Kotlin Native StableRef reference table.

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

Kotlin/Native shared code MUST NEVER hold direct strong references to Swift closure delegates when passing them across asynchronous dispatch boundaries.

Kotlin/Native shared code MUST NEVER hold direct strong references to Swift closure delegates when passing them across asynchronous dispatch boundaries.

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

Defines strict weak-reference semantics, scope termination lifecycles, and delegate decoupling across the Kotlin/Native ARC boundary to Apple Swift runtimes. Cross-language object graphs crossing this foreign function interface (FFI) lack unified cycle collectors, causing silent, non-reclaimable multi-megabyte retain cycles if strong references loop across runtimes. 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-Boundary Strong Retain Cycles Between Swift Delegates and Kotlin State Observers) 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