Claude Cursor Skill

kmp-swiftui-interop

Use when SwiftUI or Swift code consumes Kotlin Multiplatform shared logic — observing a Kotlin StateFlow or Flow from Swift, calling suspend functions with async/await, switching over Kotlin sealed classes, SKIE, KMP-NativeCoroutines, KMP-ObservableViewModel, Swift export (Kotlin

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Download kushpawan-kmp-mobile-skills-skills_kmp-swiftui-interop-c04c11f.zip · 30 KB

Install

skills CLI npx skills add https://github.com/Kushpawan/kmp-mobile-skills/tree/main/skills/kmp-swiftui-interop
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install kushpawan-kmp-mobile-skills@llmmart
Git git clone https://github.com/Kushpawan/kmp-mobile-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole kushpawan/kmp-mobile-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

KMP ↔ SwiftUI interop

Kotlin owns state and business rules; Swift owns rendering, navigation and lifecycle. The bridge between them must be thin, typed, cancellable and main-actor safe. Every bug in this seam is one of four things: a leaked collection, a state write off the main thread, a Kotlin exception Swift was never told about, or an API shape the bridge cannot express.

When to use

  • Swift code that reads Kotlin StateFlow / Flow, calls suspend functions, or switches over Kotlin sealed / enum types; shaping a Kotlin API that Swift will call.
  • Choosing or changing a bridge: Objective-C export with SKIE or KMP-NativeCoroutines, Swift export (Beta in Kotlin 2.5.0, export { swift { } }), or hand-written wrappers.
  • Hosting Compose Multiplatform in SwiftUI, or choosing it versus native SwiftUI.
  • Symptoms: UI not updating, a Kotlin ViewModel running after its screen closed, an untyped Kotlinx_coroutines_coreFlow, KotlinInt, doInitKoin(), a switch needing default, a crash naming @Throws, Sendable warnings on Kotlin types, or no launch after building with the iOS 27 SDK.

When not to use

  • Packaging the framework or the generated Swift package (XCFramework, SwiftPM, swiftPackageIntegration, KMMBridge) — use kmp-xcframework-distribution.
  • A Gradle, Kotlin/Native link or Xcode build error — use kmp-build-failure-triage.
  • Pure SwiftUI or Swift Concurrency questions with no Kotlin involved — see Related skills.

Step 0 — Read the project first

# Kotlin/Xcode versions (Kotlin 2.5.0 pairs with Xcode 27.0; 2.4.x with Xcode 26.4) and plugins
grep -n "^kotlin\s*=\|skie\|nativecoroutines\|observableviewmodel" gradle/libs.versions.toml; xcodebuild -version
# Bridge: Objective-C framework, old swiftExport {}, or export { swift {} }
grep -rn "binaries.framework\|swiftExport {\|export {\|xcodeIntegration\|swiftPackageIntegration\|co.touchlab.skie\|nativeCoroutines {" \
  --include=*.gradle.kts --include=*.toml .
# How Xcode gets Kotlin (run-script task, SwiftPM, CocoaPods)
grep -rn "embedAndSignAppleFrameworkForXcode\|embedSwiftExportForXcode" --include=project.pbxproj .
find . -name Package.swift -not -path "*/build/*"; ls Podfile 2>/dev/null
# Shared ViewModels and DI entry point
grep -rln "class .*ViewModel" --include=*.kt . | head; grep -rn "startKoin" --include=*.kt .
# Swift: deployment target, language mode, default isolation, observation style, tests
grep -rhn "IPHONEOS_DEPLOYMENT_TARGET\|SWIFT_VERSION\|SWIFT_DEFAULT_ACTOR_ISOLATION\|SWIFT_APPROACHABLE_CONCURRENCY" \
  --include=project.pbxproj . | sort | uniq -c
grep -rln "@Observable\|ObservableObject\|import Testing\|import XCTest" --include=*.swift . | head
# Host lifecycle and screen-based layout (iOS 27 SDK)
grep -rn "@main\|UIApplicationSceneManifest\|UIWindowSceneDelegate\|ComposeUIViewController\|UIScreen.main\|mainScreen\|userInterfaceIdiom" \
  --include=*.swift --include=*.plist --include=*.kt .

Record: Kotlin/Xcode versions, bridge and Swift module name, ViewModel base, DI start point, minimum iOS (@Observable 17, Swift export 18), Swift language mode and default isolation, wrapper pattern, design system, accessibility-id convention.

Follow what exists: keep an ObservableObject + Combine idiom; no SKIE in a KMP-NativeCoroutines project; never a Swift export module and an Objective-C Kotlin framework in one Xcode target. Defaults below are for new surfaces only.

Workflow

1. Decide where the UI lives (greenfield or when asked)

Factor Compose Multiplatform on iOS Native SwiftUI over shared logic
Shared / team UI and logic; Kotlin-heavy team Logic only; dedicated iOS engineers
Newest iOS UI, Swift ↔ Kotlin surface Via UIKit interop, later; one entry view Immediately; every state and action crosses

SwiftUI hosts Compose via UIViewControllerRepresentable over ComposeUIViewController { } or UIViewRepresentable over ComposeUIView { } (ComposeUIView and ComposeUIViewConfiguration are Stable in Compose Multiplatform 1.13). For content-sized Compose views, forward SwiftUI's proposal from sizeThatFits(_:uiView:context:) (iOS 16+) to uiView.sizeThatFits(…). The rest of this skill covers native SwiftUI. Done when the choice and its reason are written down.

2. Pick one bridge

Situation Bridge
Project already has one Keep it; switching is a migration
iOS below 18, CocoaPods, or Objective-C code calls Kotlin Objective-C export + SKIE or KMP-NativeCoroutines
Greenfield, iOS 18+, Kotlin 2.5.0+, a Beta is acceptable Swift export
Greenfield that must not depend on a Beta Objective-C export + SKIE on a Kotlin version SKIE supports

Check the plugin before any Kotlin upgrade. As of 3 Dec 2026, SKIE 0.10.16 supports Kotlin 2.4.21 and no SKIE release announces 2.5.0 support; KMP-NativeCoroutines has 1.0.7 for 2.4.21 and only an RC pre-release for 2.5.0. Kotlin 2.5.0 also requires Xcode 27.

Swift export (Beta): Kotlin 2.5.0+, iOS 18.0+, ENABLE_USER_SCRIPT_SANDBOXING = NO, direct integration or a generated Swift package (no CocoaPods), Swift callers only. Gradle shape:

// shared/build.gradle.kts — the Kotlin version lives in gradle/libs.versions.toml
import org.jetbrains.kotlin.gradle.swiftexport.ExperimentalSwiftExportDsl

kotlin {
    iosArm64()
    iosSimulatorArm64()
    export {
        @OptIn(ExperimentalSwiftExportDsl::class)
        swift {
            moduleName = "Shared"               // Swift: import Shared
            rootPackage = "com.example.app"     // was flattenPackage in swiftExport {}
            xcodeIntegration { }                // registers embedSwiftExportForXcode
        }
    }
}

In Xcode's Run Script phase, embedAndSignAppleFrameworkForXcode becomes ./gradlew :shared:embedSwiftExportForXcode. swiftExport { } beside export { swift { } } is a build error. Comparison table, export rules, build settings, migration and troubleshooting: references/bridging-options.md. Done when the bridge matches Step 0, or the user approved a new one with its requirements met.

3. Shape the Kotlin API for Swift

  • One entry point per screen: val state: StateFlow<NotesUiState> plus fun onAction(…); states as a sealed interface of data class / data object cases. No repositories or library types.
  • No generics at the boundary (Objective-C export keeps them only on classes, Swift export erases them). Int is Int32, Long is Int64; Objective-C export boxes nullable or generic primitives as KotlinInt, Swift export maps Int? to Int32?.
  • Neither bridge exports default arguments (SKIE has a deprecated opt-in) or reified functions such as Koin's get<T>() — add overloads and typed helpers.
  • Objective-C export renames: init… → doInit…, top-level functions on FileNameKt, NotesUiState.Content → NotesUiStateContent. Swift export keeps Kotlin names and nesting and maps packages to Swift namespaces; it drops Mutable* parameters and properties named description / hash, and names like Color or Result clash with SwiftUI.
  • @ObjCName(swiftName = "…") and @HiddenFromObjC work in both bridges; @ShouldRefineInSwift only in Objective-C export. internal is always hidden.
  • Every failing function returns a result type or declares @Throws (step 6).

Type tables for Objective-C export, SKIE and Swift export: references/type-mapping.md. Done when the generated header or Swift interface shows the intended names (Verify).

4. Write the Swift wrapper

One @MainActor model per screen mirrors Kotlin state and forwards actions. With SKIE and @Observable (iOS 17+):

import Observation
@preconcurrency import SharedKit   // Kotlin types are not Sendable; see step 5

@MainActor
@Observable
final class NotesModel {
    private(set) var state: NotesUiState
    private let viewModel: NotesViewModel   // `let` properties are not tracked by @Observable

    init(viewModel: NotesViewModel) {
        self.viewModel = viewModel
        self.state = viewModel.state.value      // first frame renders real state, not a blank
    }

    /// Mirrors Kotlin state until the calling Task is cancelled. `.task {}` cancels it on disappear.
    func observe() async {
        for await newState in viewModel.state { state = newState }
    }

    func send(_ action: NotesAction) { viewModel.onAction(action: action) }
}

struct NotesScreen: View {
    let model: NotesModel   // owned by a route container that creates it once (step 5)

    var body: some View {
        Group {
            switch onEnum(of: model.state) {
            case .loading:            ProgressView()
            case .content(let c):     NotesList(notes: c.notes, onDelete: { model.send(NotesActionDelete(id: $0)) })
            case .error(let e):       ErrorState(message: e.message)
            }
        }
        .task { await model.observe() }   // structured: cancelled automatically when the view goes away
    }
}

With Swift export: import Shared; loop over viewModel.state.asAsyncSequence() with for try await inside do { } catch { } (cancel throws CancellationError); switch model.state.sealedType() with payloads in .value (c.value.notes); NotesAction.Delete(id:). Full example with iosMain owner, Koin helper, iOS 16 variant, preview/test boundary and the Swift export variant: references/swift-wrapper-example.md. Done when state updates render and leaving the screen stops collection (Verify).

5. Get lifecycle and threading right

  • Collect in .task {}, never onAppear { Task { … } } — that Task never ends.
  • Create the model once. @State var model = NotesModel(…) re-runs the initializer on every rebuild, starting extra Kotlin ViewModels. Create it lazily in .task (if model == nil), in a route coordinator, or with ObservableObject + @StateObject.
  • Release the Kotlin side. On iOS nothing clears an androidx ViewModelStore, so viewModelScope runs forever. Own the store in an iosMain helper with clear() and call it from a small non-actor-isolated Swift handle's deinit, or from the coordinator on pop. isolated deinit (Swift 6.2) on the model also works but was reported to need iOS 18.4+ at runtime.
  • Default MainActor isolation. Xcode 26 and 27 app templates set SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor and SWIFT_APPROACHABLE_CONCURRENCY = YES; older targets keep nonisolated. Under MainActor default, declare the lifetime handle nonisolated final class, or it becomes @MainActor and its deinit cannot touch the Kotlin owner. Passing Kotlin objects into @concurrent or nonisolated code is flagged as non-Sendable.
  • Main actor and Sendable. Mark the model @MainActor; with SKIE or Swift export the for await body resumes on it although Kotlin collects elsewhere (Swift export uses Dispatchers.Default unless Kotlin calls withContext). Hand-written callbacks may arrive on any thread — hop to main first. Kotlin classes are non-Sendable: confine them to one actor (@preconcurrency import for an Objective-C framework) instead of @unchecked Sendable.

6. Make every Kotlin failure visible to Swift

Kotlin declaration Exception reaches Swift as Otherwise
non-suspend, no @Throws — App terminates (both bridges)
suspend, no @Throws (Objective-C export) Only CancellationException, as an error Anything else terminates the app
@Throws(NotesException::class, CancellationException::class) (Objective-C export) Swift throws; listed types and subclasses as NSError Unlisted types still terminate
suspend or @Throws (Swift export) async throws / throws; catch by Kotlin type; cancel → CancellationError; unexported types → KotlinRuntimeSupport.KotlinError —

Objective-C crash log: "Function doesn't have or inherit @Throws annotation…". Prefer catching in Kotlin and returning a sealed result or an error case in UiState, so Swift never needs try.

7. Start DI once, resolve through helpers

// shared/src/iosMain/kotlin/com/example/app/di/KoinIos.kt
fun initKoin() {
    startKoin { modules(sharedModule, iosPlatformModule) }
}

object NotesDependencies : KoinComponent {
    fun notesViewModelOwner(): NotesViewModelOwner = NotesViewModelOwner(get())
}
@main
struct NotesApp: App {   // SwiftUI App + WindowGroup is scene-based (step 8)
    init() { KoinIosKt.doInitKoin() }   // Objective-C export; Swift export: initKoin() or di.initKoin()
    var body: some Scene { WindowGroup { RootView() } }
}

Call it once (a second startKoin throws); never in previews or Swift tests.

8. Keep the iOS host valid for the iOS 27 SDK

Apple (WWDC26 session 278): "UIScene lifecycle is now required when building with the latest SDKs. Without it, your application will no longer launch." A UIKit AppDelegate that builds its own window around ComposeUIViewController(), with no UIWindowSceneDelegate and scene manifest, must move to scene lifecycle. iPhone apps are now resizable on iPad and in iPhone Mirroring while keeping the phone idiom: never lay out from UIScreen.main (Kotlin UIScreen.mainScreen), screen bounds, userInterfaceIdiom or orientation. Use the view's size, size classes, window?.windowScene?.screen and traitCollection.displayScale; test in the resize mode of Xcode 27's Device Hub.

9. Render natively, test the wrapper, edit Swift in Xcode

  • Use .alert, .confirmationDialog, .sheet, NavigationStack and the app's design-system tokens; no hand-rolled overlays. Give each control a stable .accessibilityIdentifier(…) from one namespace. Known traps, including an iOS 26 alert contrast issue: references/pitfalls.md.
  • Test business logic in Kotlin commonTest. Swift tests cover the wrapper through a Swift protocol (NotesSource) with a Kotlin-backed implementation and a pure Swift fake — no Kotlin runtime or DI in previews and tests.
  • From IntelliJ IDEA 2026.3 / Android Studio 2026.2.2 the KMP plugin no longer edits or navigates Swift (iOS run/debug, Swift export and Swift package import are unaffected). Edit Swift in Xcode; an agent can drive it via claude mcp add --transport stdio xcode -- xcrun mcpbridge once Xcode → Settings → Intelligence allows external agents.

Quick reference

Need Objective-C export With SKIE Swift export
Observe StateFlow<T> iosMain callback + AutoCloseable for await v in vm.state for try await v in vm.state.asAsyncSequence()
Current value Cast vm.state.value vm.state.value vm.state.value
Call suspend fun load() Completion handler; main thread by default try await vm.load() try await vm.load()
Switch over sealed UiState as? chain + fallback switch onEnum(of: s) switch s.sealedType(), payload in .value
Kotlin enum in switch Needs default: Exhaustive Exhaustive
Top-level fun x() in Util.kt UtilKt.x() same x() or pkg.x()
Minimum iOS Kotlin default 15.0 (since 2.4.0) same 18.0

Verify

Report every check as PASS, FAIL or NOT RUN with the reason. Never report a check that did not run as passed.

# 1a. Objective-C export: link for the simulator (SKIE runs here), then read the Swift-facing names
./gradlew :shared:linkDebugFrameworkIosSimulatorArm64
find shared/build/bin/iosSimulatorArm64/debugFramework -name "*.h" -path "*Headers*" \
  -exec grep -n "NotesViewModel\|NotesUiState" {} +

# 1b. Swift export: old DSL gone. Direct-integration tasks run only inside an Xcode build (check 3);
#     with swiftPackageIntegration, regenerate the package first.
grep -rn "swiftExport {" --include=*.gradle.kts . && echo "FAIL: old swiftExport {} block"
./gradlew :shared:exportDebugSwiftPackage
# 2. Kotlin tests on iOS
./gradlew :shared:iosSimulatorArm64Test
# 3. App build and Swift tests (pick a device: xcrun simctl list devices available)
xcodebuild -project iosApp/iosApp.xcodeproj -scheme iosApp \
  -destination 'platform=iOS Simulator,name=<device>' build test
  1. Lifecycle. Log _state.subscriptionCount and onCleared(); open and leave the screen: count back to 0, onCleared() ran. Otherwise NOT RUN.
  2. No new concurrency warnings in wrapper files; the iOS 27 SDK build launches; Step 0's UIScreen.main / idiom grep is clean.
  3. Swift export: run every Kotlin-backed screen — missing abstract overrides, failing as! casts and undeclared exceptions only show at runtime.

No macOS/Xcode available → checks 1–3, 5 and 6 are NOT RUN — requires macOS with Xcode.

Common mistakes

Mistake Why it bites Fix
onAppear { Task { for await … } } Collection never stops .task { await model.observe() }
Model built in @State var m = Model(vm: makeVM()) Extra Kotlin VMs start duplicate work Create lazily in .task, a coordinator, or @StateObject
Kotlin ViewModel never cleared on iOS viewModelScope keeps polling iosMain owner clear() from a handle's deinit
Kotlin function that throws, no @Throws App terminates Sealed result, or @Throws(…, CancellationException::class)
as? casts over a sealed class New subclasses fall into the fallback onEnum(of:) (SKIE) or sealedType() (Swift export)
swiftExport { } on Kotlin 2.5, or beside export { swift { } } Deprecated; both together fail the build Only export { swift { } }; flattenPackage → rootPackage
Swift export and Objective-C framework in one Xcode target Two Kotlin runtimes One bridge per target; migrate targets one at a time
Swift export with iOS < 18, CocoaPods or script sandboxing Build fails iOS 18.0+, leave CocoaPods first, ENABLE_USER_SCRIPT_SANDBOXING = NO
Coroutines or Koin as api deps of the exported module Slow or failing full export implementation, thin umbrella, SwiftExportVisibility.HIDDEN
Kotlin upgrade without checking SKIE / NativeCoroutines iOS breaks, Android stays green Check their releases for the new Kotlin first
UIKit host without scene lifecycle No launch with the iOS 27 SDK UIWindowSceneDelegate + manifest, or a SwiftUI App
Layout from UIScreen.main or idiom Wrong size in iPhone Mirroring and on iPad View size, size classes, windowScene.screen

Related skills

Files (kmp-mobile-skills)
  • references
    • bridging-options.md 14.2 KB
      Loading…
    • pitfalls.md 12.9 KB
      Loading…
    • swift-wrapper-example.md 17.5 KB
      Loading…
    • type-mapping.md 10.3 KB
      Loading…
  • SKILL.md 20.5 KB
    ---
    name: kmp-swiftui-interop
    description: 'Use when SwiftUI or Swift code consumes Kotlin Multiplatform shared logic — observing a Kotlin StateFlow or Flow from Swift, calling suspend functions with async/await, switching over Kotlin sealed classes, SKIE, KMP-NativeCoroutines, KMP-ObservableViewModel, Swift export (Kotlin 2.5 export { swift { } }, rootPackage, sealedType), @ObjCName, KotlinInt boxing, doInitKoin, a crash with "doesn''t have or inherit @Throws annotation", Sendable warnings on Kotlin types, a UIScene host for Compose Multiplatform, or Compose Multiplatform vs native SwiftUI. Not for packaging the framework.'
    license: Apache-2.0
    compatibility: Kotlin Multiplatform project whose iOS code is consumed from Swift or SwiftUI. iOS steps need macOS with Xcode (Kotlin 2.5.0 pairs with Xcode 27.0). Swift export needs Kotlin 2.5.0+ and iOS 18+; the @Observable path needs iOS 17+.
    metadata:
      category: ios-interop
      platforms: ios
    ---
    
    # KMP ↔ SwiftUI interop
    
    Kotlin owns state and business rules; Swift owns rendering, navigation and lifecycle. The bridge
    between them must be thin, typed, cancellable and main-actor safe. Every bug in this seam is one of
    four things: a leaked collection, a state write off the main thread, a Kotlin exception Swift was
    never told about, or an API shape the bridge cannot express.
    
    ## When to use
    
    - Swift code that reads Kotlin `StateFlow` / `Flow`, calls `suspend` functions, or switches over
      Kotlin sealed / enum types; shaping a Kotlin API that Swift will call.
    - Choosing or changing a bridge: Objective-C export with SKIE or KMP-NativeCoroutines, Swift export
      (Beta in Kotlin 2.5.0, `export { swift { } }`), or hand-written wrappers.
    - Hosting Compose Multiplatform in SwiftUI, or choosing it versus native SwiftUI.
    - Symptoms: UI not updating, a Kotlin ViewModel running after its screen closed, an untyped
      `Kotlinx_coroutines_coreFlow`, `KotlinInt`, `doInitKoin()`, a `switch` needing `default`, a crash
      naming `@Throws`, Sendable warnings on Kotlin types, or no launch after building with the iOS 27 SDK.
    
    ## When not to use
    
    - Packaging the framework or the generated Swift package (XCFramework, SwiftPM,
      `swiftPackageIntegration`, KMMBridge) — use `kmp-xcframework-distribution`.
    - A Gradle, Kotlin/Native link or Xcode build error — use `kmp-build-failure-triage`.
    - Pure SwiftUI or Swift Concurrency questions with no Kotlin involved — see Related skills.
    
    ## Step 0 — Read the project first
    
    ```bash
    # Kotlin/Xcode versions (Kotlin 2.5.0 pairs with Xcode 27.0; 2.4.x with Xcode 26.4) and plugins
    grep -n "^kotlin\s*=\|skie\|nativecoroutines\|observableviewmodel" gradle/libs.versions.toml; xcodebuild -version
    # Bridge: Objective-C framework, old swiftExport {}, or export { swift {} }
    grep -rn "binaries.framework\|swiftExport {\|export {\|xcodeIntegration\|swiftPackageIntegration\|co.touchlab.skie\|nativeCoroutines {" \
      --include=*.gradle.kts --include=*.toml .
    # How Xcode gets Kotlin (run-script task, SwiftPM, CocoaPods)
    grep -rn "embedAndSignAppleFrameworkForXcode\|embedSwiftExportForXcode" --include=project.pbxproj .
    find . -name Package.swift -not -path "*/build/*"; ls Podfile 2>/dev/null
    # Shared ViewModels and DI entry point
    grep -rln "class .*ViewModel" --include=*.kt . | head; grep -rn "startKoin" --include=*.kt .
    # Swift: deployment target, language mode, default isolation, observation style, tests
    grep -rhn "IPHONEOS_DEPLOYMENT_TARGET\|SWIFT_VERSION\|SWIFT_DEFAULT_ACTOR_ISOLATION\|SWIFT_APPROACHABLE_CONCURRENCY" \
      --include=project.pbxproj . | sort | uniq -c
    grep -rln "@Observable\|ObservableObject\|import Testing\|import XCTest" --include=*.swift . | head
    # Host lifecycle and screen-based layout (iOS 27 SDK)
    grep -rn "@main\|UIApplicationSceneManifest\|UIWindowSceneDelegate\|ComposeUIViewController\|UIScreen.main\|mainScreen\|userInterfaceIdiom" \
      --include=*.swift --include=*.plist --include=*.kt .
    ```
    
    Record: Kotlin/Xcode versions, bridge and Swift module name, ViewModel base, DI start point, minimum
    iOS (`@Observable` 17, Swift export 18), Swift language mode and default isolation, wrapper pattern,
    design system, accessibility-id convention.
    
    **Follow what exists:** keep an `ObservableObject` + Combine idiom; no SKIE in a KMP-NativeCoroutines
    project; never a Swift export module and an Objective-C Kotlin framework in one Xcode target.
    Defaults below are for new surfaces only.
    
    ## Workflow
    
    ### 1. Decide where the UI lives (greenfield or when asked)
    
    | Factor | Compose Multiplatform on iOS | Native SwiftUI over shared logic |
    |---|---|---|
    | Shared / team | UI and logic; Kotlin-heavy team | Logic only; dedicated iOS engineers |
    | Newest iOS UI, Swift ↔ Kotlin surface | Via UIKit interop, later; one entry view | Immediately; every state and action crosses |
    
    SwiftUI hosts Compose via `UIViewControllerRepresentable` over `ComposeUIViewController { }` or
    `UIViewRepresentable` over `ComposeUIView { }` (`ComposeUIView` and `ComposeUIViewConfiguration` are
    Stable in Compose Multiplatform 1.13). For content-sized Compose views, forward SwiftUI's proposal
    from `sizeThatFits(_:uiView:context:)` (iOS 16+) to `uiView.sizeThatFits(…)`. The rest of this skill
    covers native SwiftUI. **Done when** the choice and its reason are written down.
    
    ### 2. Pick one bridge
    
    | Situation | Bridge |
    |---|---|
    | Project already has one | Keep it; switching is a migration |
    | iOS below 18, CocoaPods, or Objective-C code calls Kotlin | Objective-C export + SKIE or KMP-NativeCoroutines |
    | Greenfield, iOS 18+, Kotlin 2.5.0+, a Beta is acceptable | Swift export |
    | Greenfield that must not depend on a Beta | Objective-C export + SKIE on a Kotlin version SKIE supports |
    
    **Check the plugin before any Kotlin upgrade.** As of 3 Dec 2026, SKIE 0.10.16 supports Kotlin
    2.4.21 and no SKIE release announces 2.5.0 support; KMP-NativeCoroutines has 1.0.7 for 2.4.21 and
    only an RC pre-release for 2.5.0. Kotlin 2.5.0 also requires Xcode 27.
    
    Swift export (Beta): Kotlin 2.5.0+, iOS 18.0+, `ENABLE_USER_SCRIPT_SANDBOXING = NO`, direct
    integration or a generated Swift package (no CocoaPods), Swift callers only. Gradle shape:
    
    ```kotlin
    // shared/build.gradle.kts — the Kotlin version lives in gradle/libs.versions.toml
    import org.jetbrains.kotlin.gradle.swiftexport.ExperimentalSwiftExportDsl
    
    kotlin {
        iosArm64()
        iosSimulatorArm64()
        export {
            @OptIn(ExperimentalSwiftExportDsl::class)
            swift {
                moduleName = "Shared"               // Swift: import Shared
                rootPackage = "com.example.app"     // was flattenPackage in swiftExport {}
                xcodeIntegration { }                // registers embedSwiftExportForXcode
            }
        }
    }
    ```
    
    In Xcode's Run Script phase, `embedAndSignAppleFrameworkForXcode` becomes
    `./gradlew :shared:embedSwiftExportForXcode`. `swiftExport { }` beside `export { swift { } }` is a
    build error. Comparison table, export rules, build settings, migration and troubleshooting:
    [references/bridging-options.md](references/bridging-options.md). **Done when** the bridge matches
    Step 0, or the user approved a new one with its requirements met.
    
    ### 3. Shape the Kotlin API for Swift
    
    - One entry point per screen: `val state: StateFlow<NotesUiState>` plus `fun onAction(…)`; states
      as a sealed interface of `data class` / `data object` cases. No repositories or library types.
    - No generics at the boundary (Objective-C export keeps them only on classes, Swift export erases
      them). `Int` is `Int32`, `Long` is `Int64`; Objective-C export boxes nullable or generic
      primitives as `KotlinInt`, Swift export maps `Int?` to `Int32?`.
    - Neither bridge exports default arguments (SKIE has a deprecated opt-in) or `reified` functions such
      as Koin's `get<T>()` — add overloads and typed helpers.
    - Objective-C export renames: `init…` → `doInit…`, top-level functions on `FileNameKt`,
      `NotesUiState.Content` → `NotesUiStateContent`. Swift export keeps Kotlin names and nesting and
      maps packages to Swift namespaces; it drops `Mutable*` parameters and properties named
      `description` / `hash`, and names like `Color` or `Result` clash with SwiftUI.
    - `@ObjCName(swiftName = "…")` and `@HiddenFromObjC` work in both bridges; `@ShouldRefineInSwift`
      only in Objective-C export. `internal` is always hidden.
    - Every failing function returns a result type or declares `@Throws` (step 6).
    
    Type tables for Objective-C export, SKIE and Swift export: [references/type-mapping.md](references/type-mapping.md).
    **Done when** the generated header or Swift interface shows the intended names (Verify).
    
    ### 4. Write the Swift wrapper
    
    One `@MainActor` model per screen mirrors Kotlin state and forwards actions. With SKIE and
    `@Observable` (iOS 17+):
    
    ```swift
    import Observation
    @preconcurrency import SharedKit   // Kotlin types are not Sendable; see step 5
    
    @MainActor
    @Observable
    final class NotesModel {
        private(set) var state: NotesUiState
        private let viewModel: NotesViewModel   // `let` properties are not tracked by @Observable
    
        init(viewModel: NotesViewModel) {
            self.viewModel = viewModel
            self.state = viewModel.state.value      // first frame renders real state, not a blank
        }
    
        /// Mirrors Kotlin state until the calling Task is cancelled. `.task {}` cancels it on disappear.
        func observe() async {
            for await newState in viewModel.state { state = newState }
        }
    
        func send(_ action: NotesAction) { viewModel.onAction(action: action) }
    }
    
    struct NotesScreen: View {
        let model: NotesModel   // owned by a route container that creates it once (step 5)
    
        var body: some View {
            Group {
                switch onEnum(of: model.state) {
                case .loading:            ProgressView()
                case .content(let c):     NotesList(notes: c.notes, onDelete: { model.send(NotesActionDelete(id: $0)) })
                case .error(let e):       ErrorState(message: e.message)
                }
            }
            .task { await model.observe() }   // structured: cancelled automatically when the view goes away
        }
    }
    ```
    
    **With Swift export:** `import Shared`; loop over `viewModel.state.asAsyncSequence()` with
    `for try await` inside `do { } catch { }` (cancel throws `CancellationError`); `switch
    model.state.sealedType()` with payloads in `.value` (`c.value.notes`); `NotesAction.Delete(id:)`.
    Full example with `iosMain` owner, Koin helper, iOS 16 variant, preview/test boundary and the Swift
    export variant: [references/swift-wrapper-example.md](references/swift-wrapper-example.md).
    **Done when** state updates render and leaving the screen stops collection (Verify).
    
    ### 5. Get lifecycle and threading right
    
    - **Collect in `.task {}`**, never `onAppear { Task { … } }` — that `Task` never ends.
    - **Create the model once.** `@State var model = NotesModel(…)` re-runs the initializer on every
      rebuild, starting extra Kotlin ViewModels. Create it lazily in `.task` (`if model == nil`), in a
      route coordinator, or with `ObservableObject` + `@StateObject`.
    - **Release the Kotlin side.** On iOS nothing clears an androidx `ViewModelStore`, so
      `viewModelScope` runs forever. Own the store in an `iosMain` helper with `clear()` and call it from
      a small non-actor-isolated Swift handle's `deinit`, or from the coordinator on pop. `isolated
      deinit` (Swift 6.2) on the model also works but was reported to need iOS 18.4+ at runtime.
    - **Default MainActor isolation.** Xcode 26 and 27 app templates set
      `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` and `SWIFT_APPROACHABLE_CONCURRENCY = YES`; older
      targets keep `nonisolated`. Under MainActor default, declare the lifetime handle
      `nonisolated final class`, or it becomes `@MainActor` and its `deinit` cannot touch the Kotlin
      owner. Passing Kotlin objects into `@concurrent` or `nonisolated` code is flagged as non-Sendable.
    - **Main actor and Sendable.** Mark the model `@MainActor`; with SKIE or Swift export the
      `for await` body resumes on it although Kotlin collects elsewhere (Swift export uses
      `Dispatchers.Default` unless Kotlin calls `withContext`). Hand-written callbacks may arrive on any
      thread — hop to main first. Kotlin classes are non-`Sendable`: confine them to one actor
      (`@preconcurrency import` for an Objective-C framework) instead of `@unchecked Sendable`.
    
    ### 6. Make every Kotlin failure visible to Swift
    
    | Kotlin declaration | Exception reaches Swift as | Otherwise |
    |---|---|---|
    | non-`suspend`, no `@Throws` | — | **App terminates** (both bridges) |
    | `suspend`, no `@Throws` (Objective-C export) | Only `CancellationException`, as an error | Anything else **terminates the app** |
    | `@Throws(NotesException::class, CancellationException::class)` (Objective-C export) | Swift `throws`; listed types and subclasses as `NSError` | Unlisted types still terminate |
    | `suspend` or `@Throws` (Swift export) | `async throws` / `throws`; catch by Kotlin type; cancel → `CancellationError`; unexported types → `KotlinRuntimeSupport.KotlinError` | — |
    
    Objective-C crash log: "Function doesn't have or inherit @Throws annotation…". Prefer catching in
    Kotlin and returning a sealed result or an error case in `UiState`, so Swift never needs `try`.
    
    ### 7. Start DI once, resolve through helpers
    
    ```kotlin
    // shared/src/iosMain/kotlin/com/example/app/di/KoinIos.kt
    fun initKoin() {
        startKoin { modules(sharedModule, iosPlatformModule) }
    }
    
    object NotesDependencies : KoinComponent {
        fun notesViewModelOwner(): NotesViewModelOwner = NotesViewModelOwner(get())
    }
    ```
    
    ```swift
    @main
    struct NotesApp: App {   // SwiftUI App + WindowGroup is scene-based (step 8)
        init() { KoinIosKt.doInitKoin() }   // Objective-C export; Swift export: initKoin() or di.initKoin()
        var body: some Scene { WindowGroup { RootView() } }
    }
    ```
    
    Call it once (a second `startKoin` throws); never in previews or Swift tests.
    
    ### 8. Keep the iOS host valid for the iOS 27 SDK
    
    Apple (WWDC26 session 278): "UIScene lifecycle is now required when building with the latest SDKs.
    Without it, your application will no longer launch." A UIKit `AppDelegate` that builds its own
    `window` around `ComposeUIViewController()`, with no `UIWindowSceneDelegate` and scene manifest, must
    move to scene lifecycle. iPhone apps are now resizable on iPad and in iPhone Mirroring while keeping
    the phone idiom: never lay out from `UIScreen.main` (Kotlin `UIScreen.mainScreen`), screen bounds,
    `userInterfaceIdiom` or orientation. Use the view's size, size classes, `window?.windowScene?.screen`
    and `traitCollection.displayScale`; test in the resize mode of Xcode 27's Device Hub.
    
    ### 9. Render natively, test the wrapper, edit Swift in Xcode
    
    - Use `.alert`, `.confirmationDialog`, `.sheet`, `NavigationStack` and the app's design-system
      tokens; no hand-rolled overlays. Give each control a stable `.accessibilityIdentifier(…)` from one
      namespace. Known traps, including an iOS 26 alert contrast issue: [references/pitfalls.md](references/pitfalls.md).
    - Test business logic in Kotlin `commonTest`. Swift tests cover the wrapper through a Swift protocol
      (`NotesSource`) with a Kotlin-backed implementation and a pure Swift fake — no Kotlin runtime or
      DI in previews and tests.
    - From IntelliJ IDEA 2026.3 / Android Studio 2026.2.2 the KMP plugin no longer edits or navigates
      Swift (iOS run/debug, Swift export and Swift package import are unaffected). Edit Swift in Xcode;
      an agent can drive it via `claude mcp add --transport stdio xcode -- xcrun mcpbridge` once
      Xcode → Settings → Intelligence allows external agents.
    
    ## Quick reference
    
    | Need | Objective-C export | With SKIE | Swift export |
    |---|---|---|---|
    | Observe `StateFlow<T>` | `iosMain` callback + `AutoCloseable` | `for await v in vm.state` | `for try await v in vm.state.asAsyncSequence()` |
    | Current value | Cast `vm.state.value` | `vm.state.value` | `vm.state.value` |
    | Call `suspend fun load()` | Completion handler; main thread by default | `try await vm.load()` | `try await vm.load()` |
    | Switch over sealed `UiState` | `as?` chain + fallback | `switch onEnum(of: s)` | `switch s.sealedType()`, payload in `.value` |
    | Kotlin `enum` in `switch` | Needs `default:` | Exhaustive | Exhaustive |
    | Top-level `fun x()` in `Util.kt` | `UtilKt.x()` | same | `x()` or `pkg.x()` |
    | Minimum iOS | Kotlin default 15.0 (since 2.4.0) | same | 18.0 |
    
    ## Verify
    
    Report every check as `PASS`, `FAIL` or `NOT RUN` with the reason. Never report a check that did
    not run as passed.
    
    ```bash
    # 1a. Objective-C export: link for the simulator (SKIE runs here), then read the Swift-facing names
    ./gradlew :shared:linkDebugFrameworkIosSimulatorArm64
    find shared/build/bin/iosSimulatorArm64/debugFramework -name "*.h" -path "*Headers*" \
      -exec grep -n "NotesViewModel\|NotesUiState" {} +
    
    # 1b. Swift export: old DSL gone. Direct-integration tasks run only inside an Xcode build (check 3);
    #     with swiftPackageIntegration, regenerate the package first.
    grep -rn "swiftExport {" --include=*.gradle.kts . && echo "FAIL: old swiftExport {} block"
    ./gradlew :shared:exportDebugSwiftPackage
    # 2. Kotlin tests on iOS
    ./gradlew :shared:iosSimulatorArm64Test
    # 3. App build and Swift tests (pick a device: xcrun simctl list devices available)
    xcodebuild -project iosApp/iosApp.xcodeproj -scheme iosApp \
      -destination 'platform=iOS Simulator,name=<device>' build test
    ```
    
    4. **Lifecycle.** Log `_state.subscriptionCount` and `onCleared()`; open and leave the screen: count
       back to 0, `onCleared()` ran. Otherwise `NOT RUN`.
    5. No new concurrency warnings in wrapper files; the iOS 27 SDK build launches; Step 0's
       `UIScreen.main` / idiom grep is clean.
    6. Swift export: run every Kotlin-backed screen — missing abstract overrides, failing `as!` casts
       and undeclared exceptions only show at runtime.
    
    No macOS/Xcode available → checks 1–3, 5 and 6 are `NOT RUN — requires macOS with Xcode`.
    
    ## Common mistakes
    
    | Mistake | Why it bites | Fix |
    |---|---|---|
    | `onAppear { Task { for await … } }` | Collection never stops | `.task { await model.observe() }` |
    | Model built in `@State var m = Model(vm: makeVM())` | Extra Kotlin VMs start duplicate work | Create lazily in `.task`, a coordinator, or `@StateObject` |
    | Kotlin ViewModel never cleared on iOS | `viewModelScope` keeps polling | `iosMain` owner `clear()` from a handle's `deinit` |
    | Kotlin function that throws, no `@Throws` | App terminates | Sealed result, or `@Throws(…, CancellationException::class)` |
    | `as?` casts over a sealed class | New subclasses fall into the fallback | `onEnum(of:)` (SKIE) or `sealedType()` (Swift export) |
    | `swiftExport { }` on Kotlin 2.5, or beside `export { swift { } }` | Deprecated; both together fail the build | Only `export { swift { } }`; `flattenPackage` → `rootPackage` |
    | Swift export and Objective-C framework in one Xcode target | Two Kotlin runtimes | One bridge per target; migrate targets one at a time |
    | Swift export with iOS < 18, CocoaPods or script sandboxing | Build fails | iOS 18.0+, leave CocoaPods first, `ENABLE_USER_SCRIPT_SANDBOXING = NO` |
    | Coroutines or Koin as `api` deps of the exported module | Slow or failing full export | `implementation`, thin umbrella, `SwiftExportVisibility.HIDDEN` |
    | Kotlin upgrade without checking SKIE / NativeCoroutines | iOS breaks, Android stays green | Check their releases for the new Kotlin first |
    | UIKit host without scene lifecycle | No launch with the iOS 27 SDK | `UIWindowSceneDelegate` + manifest, or a SwiftUI `App` |
    | Layout from `UIScreen.main` or idiom | Wrong size in iPhone Mirroring and on iPad | View size, size classes, `windowScene.screen` |
    
    ## Related skills
    
    - `kmp-xcframework-distribution` — packaging (XCFramework, SwiftPM, `swiftPackageIntegration`).
    - `kmp-build-failure-triage` (link and run-script errors), `kmp-crash-triage` (`@Throws` terminations),
      `compose-multiplatform-screen` (Compose UI), `mobile-platform-parity` (resizable iPhone layouts).
    - [Kotlin agent skills](https://github.com/Kotlin/kotlin-agent-skills) — CocoaPods → SwiftPM
      migration, a prerequisite for Swift export.
    - Apple's Xcode 27 skills, including app modernization (scene lifecycle, resizing):
      `xcrun agent skills export --output-dir <dir>`.
    - [SwiftUI Expert](https://github.com/AvdLee/SwiftUI-Agent-Skill), [SwiftUI Pro](https://github.com/twostraws/SwiftUI-Agent-Skill),
      [Swift Concurrency](https://github.com/AvdLee/Swift-Concurrency-Agent-Skill); [MobileBuildMCP](https://github.com/getsentry/MobileBuildMCP) for agent builds.
    - Docs: [Swift export](https://kotlinlang.org/docs/native-swift-export.html), [Objective-C/Swift interop](https://kotlinlang.org/docs/native-objc-interop.html),
      [SKIE](https://skie.touchlab.co), [Compose in SwiftUI](https://kotlinlang.org/docs/multiplatform/compose-swiftui-integration.html),
      [WWDC26 session 278](https://developer.apple.com/videos/play/wwdc2026/278/).
    

Comments

Sign in to join the conversation.

No comments yet. Start the conversation.

Reviews (0)

No reviews yet.