iOS integration and Swift interop

Learn how Kotlin Multiplatform exposes shared Kotlin code to Swift on iOS: the Objective-C header, suspend functions as async, Flow with SKIE, and iOS targets. About 25 minutes.

Why it matters

  • Most Kotlin Multiplatform (KMP) teams ship one shared module consumed by both the Android app and an iOS app. The Swift side is where bugs hide: UI updated off the main thread, exceptions that crash instead of throwing, Flows that are never cancelled. Senior KMP interviews probe exactly these seams.
  • Kotlin/Native compiles the shared module into an Apple .framework with a generated Objective-C header, and Swift imports it. Knowing the mapping (suspend becomes a completion handler that Swift can await, Flow needs a wrapper) saves hours of interop debugging.
  • The Gradle setup for iOS targets (iosArm64(), iosSimulatorArm64()) and the binaries.framework block is the first thing to configure. A missing target means the app fails to build for devices or for the simulator on Apple Silicon Macs.
  • Exceptions follow strict rules across the boundary. A Kotlin exception that is not declared with @Throws terminates the iOS app, which surprises Android developers used to catching anything.

The simple explanation

How does Swift call Kotlin code in a KMP project? Kotlin/Native compiles the shared module for each iOS target into a .framework. The compiler also generates an Objective-C header describing every public Kotlin declaration. Swift imports the framework (import Shared) and calls Kotlin classes and functions as if they were Objective-C APIs. Swift never sees Kotlin directly, only this Objective-C view of it.

  • Think of the generated header as a menu: it lists what the kitchen (Kotlin/Native) can serve, written in the language the waiter (Swift) reads. Anything that does not translate well to Objective-C (generic interfaces, sealed hierarchies, default arguments) comes out less pleasant on the menu.
  • A suspend function is a takeaway order: you place it and get called back when it is ready. Swift can wrap that callback in await.
  • A Flow is a live feed. Objective-C has no equivalent, so a wrapper such as SKIE turns it into a Swift AsyncSequence.

Key mappings Swift sees:

KotlinSwift (plain Kotlin/Native export)Swift (with SKIE)
suspend fun f(): Tf(completionHandler: (T?, Error?) -> Void), also callable as try await f()try await f() with cancellation passed to Kotlin
Flow<T>An Objective-C protocol with collect(collector:completionHandler:); the element type is lostAsyncSequence you can loop with for await
data class UserA Swift class (reference type); copy is exported as doCopysame
String? / StringString? / Stringsame
sealed classA class hierarchy, so switch is not exhaustiveExhaustive Swift enum via onEnum(of:)

The Gradle side declares the iOS targets and the framework:

kotlin {
    androidTarget()
    listOf(iosArm64(), iosSimulatorArm64()).forEach { target ->
        target.binaries.framework {
            baseName = "Shared"
            isStatic = true
        }
    }
}

The default hierarchy template creates iosMain automatically and makes every iOS target's source set depend on it. iosArm64 covers devices and iosSimulatorArm64 covers the simulator on Apple Silicon Macs. iosX64 is only for the simulator on Intel Macs and is being phased out by Kotlin, so add it only if your team still uses Intel Macs.

SKIE (a Gradle plugin from Touchlab) and KMP-NativeCoroutines are the two common bridges for coroutines. Swift can already await a suspend function, but cancelling the Swift Task does not cancel the Kotlin coroutine, and a raw Flow is not usable without writing a collector by hand. Swift export, which generates Swift APIs directly instead of going through Objective-C, is still experimental.

Notes

  • The framework is written to build/bin/<target>/debugFramework/ (or releaseFramework/), for example build/bin/iosArm64/debugFramework/Shared.framework/Headers/Shared.h. Read this header to see exactly what Swift gets.
  • binaries.framework builds a dynamic framework unless you set isStatic = true. Project templates often set isStatic = true, and the Kotlin docs suggest a static framework when a dynamic one causes duplicate-symbol or linking errors in Xcode. With a static framework there is nothing to embed at runtime; with a dynamic one Xcode must embed it.
  • Kotlin suspend functions become Objective-C methods with a completionHandler that receives a result and an error. Since Swift 5.5 you can call them with try await. Kotlin documents this async bridging as experimental, and Swift cancellation does not reach the coroutine.
  • Do not assume which thread a completion handler or an awaited call returns on. Update UI from a @MainActor function or hop to DispatchQueue.main.
  • A suspend function without @Throws propagates only CancellationException as an NSError. Any other Kotlin exception reaching Swift is unhandled and terminates the app. Annotate the API with @Throws(IOException::class) or return a result type instead.
  • Non-suspend functions without @Throws propagate no Kotlin exceptions at all; an exception escaping them crashes the app.
  • Flow exports as an Objective-C protocol without its type parameter. Use SKIE (turns it into an AsyncSequence) or KMP-NativeCoroutines (async sequences, Combine publishers or RxSwift observables via a Swift package) rather than hand-written collectors.
  • In Objective-C, Kotlin class names get a prefix derived from the framework name; Swift usually sees the plain name. @ObjCName("Name") sets a custom Objective-C and Swift name and needs @OptIn(ExperimentalObjCName::class).
  • Top-level functions are exported on a class named after the file, such as KoinKt for Koin.kt. Names that clash with Objective-C conventions get a do prefix, so fun initKoin() is called from Swift as KoinKt.doInitKoin().
  • Kotlin nullability maps directly: String? becomes Swift String? and String stays non-optional, so the Swift compiler checks nulls at the boundary.
  • Generics survive on classes but not on interfaces, which is one reason Flow (an interface) loses its element type in Swift.
  • Hilt and Dagger are JVM/Android-only. Use Koin, kotlin-inject or manual constructor injection in shared code that iOS consumes.

Code example

This Swift file consumes a KMP framework called Shared. It calls a suspend function with async/await, collects a Flow that SKIE has turned into an AsyncSequence, and ties the collection to a SwiftUI view's lifetime.

// commonMain (IOException from kotlinx.io)
class UserRepository(private val api: UserApi) {
    @Throws(IOException::class)
    suspend fun fetchUser(id: String): User? = api.user(id)
 
    fun observeUsers(): Flow<List<User>> = api.userUpdates()
}
import SwiftUI
import Shared
 
@MainActor
final class ProfileModel: ObservableObject {
    @Published var title = "Loading"
    @Published var names: [String] = []
    private let repo: UserRepository
 
    init(repo: UserRepository) {
        self.repo = repo
    }
 
    // Kotlin: @Throws(IOException::class) suspend fun fetchUser(id: String): User?
    func load() async {
        do {
            let user = try await repo.fetchUser(id: "42")
            title = user?.name ?? "Unknown user"
        } catch {
            title = "Offline"
        }
    }
 
    // Kotlin: fun observeUsers(): Flow<List<User>>
    // SKIE exposes the Flow as an AsyncSequence
    func observe() async {
        for await users in repo.observeUsers() {
            names = users.map { $0.name }
        }
    }
}
 
struct ProfileView: View {
    @StateObject var model: ProfileModel
 
    var body: some View {
        List(model.names, id: \.self) { Text($0) }
            .navigationTitle(model.title)
            .task { await model.load() }
            .task { await model.observe() }
    }
}
  • ProfileModel is @MainActor, so the @Published properties are updated on the main thread after each await, whichever thread Kotlin finished on.
  • fetchUser is declared with @Throws(IOException::class), so a network failure arrives as a Swift error caught by catch. Without @Throws, an IOException would terminate the app.
  • SwiftUI's .task cancels its Task when the view disappears. With SKIE, that cancellation reaches the Kotlin coroutine collecting the Flow, so nothing keeps running after the screen is gone.
  • User is a Kotlin data class, exported to Swift as a class. Its name property is a non-optional String, so no unwrapping is needed.

Run the idea in plain Kotlin

This models the bridge Kotlin/Native generates for a suspend function: Swift receives a completion handler with a result or an error. Only CancellationException and exceptions listed in @Throws become an error; anything else terminates the app.

import kotlin.coroutines.cancellation.CancellationException

class NetworkException(message: String) : Exception(message)

data class User(val id: String, val name: String, val email: String?)

// Models the generated completion handler: (result?, error?)
fun <T> callFromSwift(
  declaredThrows: List<(Throwable) -> Boolean>,
  body: () -> T,
  completion: (T?, String?) -> Unit,
) {
  val result = try {
      body()
  } catch (e: Throwable) {
      val propagated = e is CancellationException || declaredThrows.any { it(e) }
      if (propagated) completion(null, "NSError: " + e.message)
      else println("Unhandled " + e::class.simpleName + ": app terminates")
      return
  }
  completion(result, null)
}

val users = mapOf("42" to User("42", "Ada", null))

fun fetchUser(id: String): User? {
  if (id == "offline") throw NetworkException("no connection")
  return users[id]
}

fun main() {
  val withThrows = listOf<(Throwable) -> Boolean>({ it is NetworkException })
  val withoutThrows = emptyList<(Throwable) -> Boolean>()

  for (id in listOf("42", "7", "offline")) {
      callFromSwift(withThrows, { fetchUser(id) }) { user, error ->
          when {
              error != null -> println(id + " -> " + error)
              user == null -> println(id + " -> nil")
              else -> println(id + " -> " + user.name + " <" + (user.email ?: "N/A") + ">")
          }
      }
  }

  // Same call, but the Kotlin function has no @Throws
  callFromSwift(withoutThrows, { fetchUser("offline") }) { _, error ->
      println("never printed: " + error)
  }
}

Expected output:

42 -> Ada <N/A>
7 -> nil
offline -> NSError: no connection
Unhandled NetworkException: app terminates

In production

A dismissed screen kept collecting a Flow
  • After a release, the iOS app's memory and network use grew every time users opened and closed the feed screen.
  • The view controller collected a Kotlin Flow with a hand-written FlowCollector in Swift, started in viewDidLoad, and never cancelled it.
  • Each visit started another collector that kept running in Kotlin after the screen was dismissed, holding references to the old view controllers.
The fix
  • The team applied the SKIE Gradle plugin to the shared module and replaced the hand-written collector with a for await loop over the AsyncSequence SKIE generates.
  • They started the loop in a Task stored on the view controller and cancelled it in viewDidDisappear; in SwiftUI screens they used the .task modifier, which cancels automatically.
  • They checked with the Xcode memory graph that no feed view controllers remained after opening and closing the screen repeatedly.
Missing iosSimulatorArm64 target broke simulator builds
  • New hires on Apple Silicon Macs could not run the app in the simulator; Xcode failed because no framework was built for the arm64 simulator.
  • The Gradle file declared only iosArm64() and iosX64(). Older Intel Macs ran the simulator through iosX64(), so nobody had noticed.
The fix
  • The team added iosSimulatorArm64() with the same binaries.framework configuration and moved the target list into a convention plugin shared by every KMP module.
  • CI now links both frameworks, for example ./gradlew :shared:linkDebugFrameworkIosArm64 :shared:linkDebugFrameworkIosSimulatorArm64, and builds the iOS app for the simulator.
  • Once no one used Intel Macs, they removed iosX64(), which also shortened builds.

Common mistakes

  • Hand-collecting a Flow in Swift. The exported Flow protocol loses its type and gives you no cancellation handle, so hand-written collectors leak. Use SKIE or KMP-NativeCoroutines and tie collection to a cancellable Task.
  • Updating UI from wherever Kotlin called back. Do not assume the completion handler or the code after await runs on the main thread. Mark view models @MainActor or hop to DispatchQueue.main before touching UIKit or SwiftUI state.
  • Forgetting @Throws on APIs that can fail. Without it, a suspend function propagates only CancellationException; an IOException from Ktor terminates the iOS app. Declare the exceptions with @Throws or return a sealed result type.
  • Missing the Apple Silicon simulator target. iosSimulatorArm64() is needed to run on the simulator on Apple Silicon Macs. iosX64() alone covers only Intel Macs.
  • Assuming Swift cancellation reaches Kotlin. Calling a suspend function with plain await does not cancel the coroutine when the Swift Task is cancelled. SKIE and KMP-NativeCoroutines add that.
  • Exposing Kotlin-only API shapes to Swift. Sealed classes, default arguments and generic interfaces come out awkward through Objective-C. Design a small Swift-facing API in the shared module and check the generated header (or use SKIE for sealed classes and default arguments).

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How does Kotlin/Native expose shared code to Swift?”

“How do you consume a Kotlin Flow from Swift?”

“What happens with threads and errors when Swift calls a Kotlin suspend function?”

“How do you set up iOS targets and frameworks in the KMP Gradle build?”

Quiz

How does a Kotlin suspend function appear to Swift without SKIE?

Which targets are needed to run a KMP framework on iPhones and in the simulator on an Apple Silicon Mac?

A Kotlin suspend function without @Throws throws an IOException when called from Swift. What happens?

Why do teams add SKIE or KMP-NativeCoroutines when Swift consumes Flows?

0 of 4 answered

Mini task

Export a suspend function and call it from Swift (20 min)

Goal: Build an iOS framework from a KMP module, export a suspend function, and call it from Swift with async/await.

  1. In the KMP module's build.gradle.kts, declare iosArm64() and iosSimulatorArm64(), each with binaries.framework { baseName = "SharedDemo"; isStatic = true } as in the Explain section.

  2. In commonMain, add:

    class GreetingService {
        @Throws(IllegalArgumentException::class)
        suspend fun greet(name: String): String {
            require(name.isNotBlank()) { "name is blank" }
            return "Hello, " + name
        }
    }
  3. Run ./gradlew linkDebugFrameworkIosSimulatorArm64. Open build/bin/iosSimulatorArm64/debugFramework/SharedDemo.framework/Headers/SharedDemo.h and find the greet method with its completionHandler parameter.

  4. Connect the framework to an Xcode iOS app. The simplest reliable way is to create the project with the Kotlin Multiplatform wizard, which adds the embedAndSignAppleFrameworkForXcode build phase. In a SwiftUI view, add:

    import SwiftUI
    import SharedDemo
     
    struct GreetingView: View {
        @State private var message = "..."
     
        var body: some View {
            Text(message)
                .task {
                    do {
                        message = try await GreetingService().greet(name: "World")
                    } catch {
                        message = "Error: \(error.localizedDescription)"
                    }
                }
        }
    }
  5. Run the app on an iOS simulator. Then change the argument to an empty string and run again.

Done condition: the screen shows Hello, World; with an empty name it shows an error instead of crashing. Remove @Throws and the empty-name case terminates the app, which shows why the annotation matters.

Next: KMP architecture and DI