This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-2-1-swift-export-abi-layout-invariant

Kotlin Multiplatform 2.1 Swift Export Direct ABI Value Layout

Enforces direct Swift-Kotlin value-type memory alignment via Kotlin 2.1+ Swift Export, bypassing the legacy Objective-C runtime bridge. Eliminates heap allocations and boxing overhead (NSNumber/NSObject wrappers) on high-throughput native iOS execution paths. Guarantees predictable unboxed struct and scalar mappings across the native binary interface.

Prohibited Anti-Pattern: Routing High-Frequency Data Across Legacy Obj-C XCFramework Bridges Inducing NSNumber Boxing and objc_msgSend Overhead

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform 2.1 Swift Export Direct ABI Value Layout - Enforces direct Swift-Kotlin value-type memory alignment via Kotlin 2.1+ Swift Export, bypassing the legacy Objective-C runtime bridge. Eliminates heap allocations and boxing overhead (NSNumber/NSObject wrappers) on high-throughput native iOS execution paths. Guarantees predictable unboxed struct and scalar mappings across the native binary interface.
globs: **/build.gradle.kts, gradle.properties, **/src/commonMain/kotlin/**/*.kt, **/src/iosMain/kotlin/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-2-1-swift-export-abi-layout-invariant"
---

# Kotlin Multiplatform 2.1 Swift Export Direct ABI Value Layout

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Routing High-Frequency Data Across Legacy Obj-C XCFramework Bridges Inducing NSNumber Boxing and objc_msgSend Overhead

## System Constraints
You are a Principal Software Architect enforcing Kotlin Multiplatform 2.1+ Swift Export ABI layout invariants. Your mandate is to eliminate all Objective-C bridging overhead, boxing allocations (NSNumber/KotlinBase), and dynamic objc_msgSend dispatch for native iOS interop. Enforce direct Swift value-type struct and scalar alignment through direct Swift Export toolchains, strict layout declarations, and unboxed primitive representations across the shared boundary.

## Strict Guidelines
- Engineers MUST ALWAYS enable 'kotlin.experimental.swift-export.enabled=true' in gradle.properties when targeting direct Swift interop in Kotlin 2.1+.
- Engineers MUST NOT expose nullable primitives (e.g., Int?, Double?) or polymorphic interfaces on high-frequency interop boundaries that force heap boxing into reference containers.
- Data contracts intended for native iOS consumption MUST be structured as flat data classes or value classes that map deterministically to Swift value-type structs.
- Build scripts MUST configure the native binary target via 'swiftExport {}' block in the Kotlin Multiplatform Gradle DSL instead of relying solely on legacy Objective-C framework export.
- Shared APIs MUST NOT rely on Foundation framework types (e.g., NSString, NSArray, NSNumber) inside the core ABI surface; use standard Kotlin types mapped to native Swift primitives.
- Components NEVER execute tight loop mutations across bridged dynamic reference interfaces; enforce batched memory or contiguous native primitive arrays.

## Bad vs Good Implementations
### Gradle Build & Model Definition: Legacy Obj-C Bridge vs Direct Swift Export ABI

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy Obj-C framework generation wraps Double? and primitive types into NSNumber references. TelemetryPoint is projected as an Obj-C class inheriting from KotlinBase, requiring heap allocation for every instance and dynamic message dispatch (objc_msgSend) across the Swift-Kotlin bridge.
```kotlin
// build.gradle.kts - Anti-pattern: Relying on legacy Obj-C XCFramework export
kotlin {
    iosArm64 {
        binaries.framework {
            baseName = "SharedCore"
            isStatic = true
        }
    }
}

// commonMain/kotlin/TelemetryPoint.kt
// Exposing boxed primitives and untyped containers across legacy Obj-C runtime
data class TelemetryPoint(
    val timestamp: Long,
    val metricId: String?,
    val value: Double? // Forces NSNumber reference boxing on iOS runtime
)

interface TelemetryPipeline {
    fun pushBatch(points: List<Any>) // Dynamic casting and KotlinBase wrapping
}
```

#### Production Standard (Correct)
> **Standard**: Configuring Kotlin 2.1 Swift Export generates pure Swift interfaces and native Swift value structs. Non-nullable primitives map directly to Swift.Double and Swift.Int64, eliminating heap allocations, reference counting overhead, and Objective-C runtime indirection.
```kotlin
// gradle.properties: kotlin.experimental.swift-export.enabled=true

// build.gradle.kts - Production standard: Direct Swift Export with native ABI alignment
kotlin {
    iosArm64()
    iosSimulatorArm64()

    swiftExport {
        // Direct Swift Export configuration in KMP 2.1+
        moduleName.set("SharedCore")
    }
}

// commonMain/kotlin/TelemetryPoint.kt
// Flat, non-nullable value structures that lower directly to Swift struct memory layouts
@OptIn(kotlin.experimental.ExperimentalObjCName::class)
data class TelemetryPoint(
    val timestampMs: Long,
    val metricId: Long,
    val value: Double // Emitted directly as Swift.Double without reference boxing
)

interface TelemetryPipeline {
    fun pushBatch(points: DoubleArray, count: Int) // Contiguous buffer avoiding object boxing
}
```

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 2.1 Swift Export Direct ABI Value Layout

Kotlin Multiplatform 2.1 Swift Export Direct ABI Value Layout defines an industrial-grade behavioral standard for mobile engineering. Enforces direct Swift-Kotlin value-type memory alignment via Kotlin 2.1+ Swift Export, bypassing the legacy Objective-C runtime bridge. Eliminates heap allocations and boxing overhead (NSNumber/NSObject wrappers) on high-throughput native iOS execution paths. Guarantees predictable unboxed struct and scalar mappings across the native binary interface. 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: Routing High-Frequency Data Across Legacy Obj-C XCFramework Bridges Inducing NSNumber Boxing and objc_msgSend Overhead 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 DriftRouting High-Frequency Data Across Legacy Obj-C XCFramework Bridges Inducing NSNumber Boxing and objc_msgSend OverheadCritical
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 enable 'kotlin.experimental.swift-export.enabled=true' in gradle.properties when targeting direct Swift interop in Kotlin 2.1+.

Engineers MUST ALWAYS enable 'kotlin.experimental.swift-export.enabled=true' in gradle.properties when targeting direct Swift interop in Kotlin 2.1+.

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 expose nullable primitives (e.g., Int?, Double?) or polymorphic interfaces on high-frequency interop boundaries that force heap boxing into reference containers.

Engineers MUST NOT expose nullable primitives (e.g., Int?, Double?) or polymorphic interfaces on high-frequency interop boundaries that force heap boxing into reference containers.

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

Data contracts intended for native iOS consumption MUST be structured as flat data classes or value classes that map deterministically to Swift value-type structs.

Data contracts intended for native iOS consumption MUST be structured as flat data classes or value classes that map deterministically to Swift value-type structs.

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

Build scripts MUST configure the native binary target via 'swiftExport {}' block in the Kotlin Multiplatform Gradle DSL instead of relying solely on legacy Objective-C framework export.

Build scripts MUST configure the native binary target via 'swiftExport {}' block in the Kotlin Multiplatform Gradle DSL instead of relying solely on legacy Objective-C framework export.

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

Shared APIs MUST NOT rely on Foundation framework types (e.g., NSString, NSArray, NSNumber) inside the core ABI surface

Shared APIs MUST NOT rely on Foundation framework types (e.g., NSString, NSArray, NSNumber) inside the core ABI surface; use standard Kotlin types mapped to native Swift 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.
6

Components NEVER execute tight loop mutations across bridged dynamic reference interfaces

Components NEVER execute tight loop mutations across bridged dynamic reference interfaces; enforce batched memory or contiguous native primitive arrays.

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 2.1 Swift Export Direct ABI Value Layout critical for AI coding assistants?

Enforces direct Swift-Kotlin value-type memory alignment via Kotlin 2.1+ Swift Export, bypassing the legacy Objective-C runtime bridge. Eliminates heap allocations and boxing overhead (NSNumber/NSObject wrappers) on high-throughput native iOS execution paths. Guarantees predictable unboxed struct and scalar mappings across the native binary interface. 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 (Routing High-Frequency Data Across Legacy Obj-C XCFramework Bridges Inducing NSNumber Boxing and objc_msgSend Overhead) 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