iOS integration and Swift interop
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
.frameworkwith a generated Objective-C header, and Swift imports it. Knowing the mapping (suspend becomes a completion handler that Swift canawait,Flowneeds a wrapper) saves hours of interop debugging. - The Gradle setup for iOS targets (
iosArm64(),iosSimulatorArm64()) and thebinaries.frameworkblock 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
@Throwsterminates 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
suspendfunction is a takeaway order: you place it and get called back when it is ready. Swift can wrap that callback inawait. - A
Flowis a live feed. Objective-C has no equivalent, so a wrapper such as SKIE turns it into a SwiftAsyncSequence.
Key mappings Swift sees:
| Kotlin | Swift (plain Kotlin/Native export) | Swift (with SKIE) |
|---|---|---|
suspend fun f(): T | f(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 lost | AsyncSequence you can loop with for await |
data class User | A Swift class (reference type); copy is exported as doCopy | same |
String? / String | String? / String | same |
sealed class | A class hierarchy, so switch is not exhaustive | Exhaustive 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/(orreleaseFramework/), for examplebuild/bin/iosArm64/debugFramework/Shared.framework/Headers/Shared.h. Read this header to see exactly what Swift gets. binaries.frameworkbuilds a dynamic framework unless you setisStatic = true. Project templates often setisStatic = 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
suspendfunctions become Objective-C methods with acompletionHandlerthat receives a result and an error. Since Swift 5.5 you can call them withtry 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
@MainActorfunction or hop toDispatchQueue.main. - A suspend function without
@Throwspropagates onlyCancellationExceptionas anNSError. 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
@Throwspropagate no Kotlin exceptions at all; an exception escaping them crashes the app. Flowexports as an Objective-C protocol without its type parameter. Use SKIE (turns it into anAsyncSequence) 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
KoinKtforKoin.kt. Names that clash with Objective-C conventions get adoprefix, sofun initKoin()is called from Swift asKoinKt.doInitKoin(). - Kotlin nullability maps directly:
String?becomes SwiftString?andStringstays 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() }
}
}ProfileModelis@MainActor, so the@Publishedproperties are updated on the main thread after eachawait, whichever thread Kotlin finished on.fetchUseris declared with@Throws(IOException::class), so a network failure arrives as a Swift error caught bycatch. Without@Throws, anIOExceptionwould terminate the app.- SwiftUI's
.taskcancels itsTaskwhen the view disappears. With SKIE, that cancellation reaches the Kotlin coroutine collecting theFlow, so nothing keeps running after the screen is gone. Useris a Kotlindata class, exported to Swift as a class. Itsnameproperty is a non-optionalString, 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
- 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
Flowwith a hand-writtenFlowCollectorin Swift, started inviewDidLoad, 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 team applied the SKIE Gradle plugin to the shared module and replaced the hand-written collector with a
for awaitloop over theAsyncSequenceSKIE generates. - They started the loop in a
Taskstored on the view controller and cancelled it inviewDidDisappear; in SwiftUI screens they used the.taskmodifier, which cancels automatically. - They checked with the Xcode memory graph that no feed view controllers remained after opening and closing the screen repeatedly.
- 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()andiosX64(). Older Intel Macs ran the simulator throughiosX64(), so nobody had noticed.
- The team added
iosSimulatorArm64()with the samebinaries.frameworkconfiguration 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
Flowprotocol loses its type and gives you no cancellation handle, so hand-written collectors leak. Use SKIE or KMP-NativeCoroutines and tie collection to a cancellableTask. - Updating UI from wherever Kotlin called back. Do not assume the completion handler or the code after
awaitruns on the main thread. Mark view models@MainActoror hop toDispatchQueue.mainbefore touching UIKit or SwiftUI state. - Forgetting
@Throwson APIs that can fail. Without it, a suspend function propagates onlyCancellationException; anIOExceptionfrom Ktor terminates the iOS app. Declare the exceptions with@Throwsor 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
awaitdoes not cancel the coroutine when the SwiftTaskis 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.
-
In the KMP module's
build.gradle.kts, declareiosArm64()andiosSimulatorArm64(), each withbinaries.framework { baseName = "SharedDemo"; isStatic = true }as in the Explain section. -
In
commonMain, add:class GreetingService { @Throws(IllegalArgumentException::class) suspend fun greet(name: String): String { require(name.isNotBlank()) { "name is blank" } return "Hello, " + name } } -
Run
./gradlew linkDebugFrameworkIosSimulatorArm64. Openbuild/bin/iosSimulatorArm64/debugFramework/SharedDemo.framework/Headers/SharedDemo.hand find thegreetmethod with itscompletionHandlerparameter. -
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
embedAndSignAppleFrameworkForXcodebuild 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)" } } } } -
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.