Kotlin Multiplatform iOS — Complete Guide
In this tutorial, you'll learn about Kotlin Multiplatform iOS. We cover key concepts, practical examples, and best practices.
The Problem
Your KMP iOS framework fails to build, or the exported Kotlin classes aren't accessible from Swift.
Wrong Approach ❌
// Not configuring iOS framework export
kotlin {
iosX64()
iosArm64()
iosSimulatorArm64()
// Missing framework configuration
}
Output: No iOS framework produced. Swift project can't import Kotlin code.
Right Approach ✅
// build.gradle.kts — shared module
kotlin {
iosX64()
iosArm64()
iosSimulatorArm64()
listOf(iosX64(), iosArm64(), iosSimulatorArm64()).forEach {
it.binaries.framework {
baseName = "shared"
isStatic = true
// Export dependencies
export("org.jetbrains.kotlinx:kotlinx-coroutines-core")
export("org.jetbrains.kotlinx:kotlinx-serialization-json")
// Objective-C interop
@Suppress("UNUSED")
configure frameworks {
baseName = "shared"
// For custom module name
moduleName = "SharedKMP"
}
}
}
sourceSets {
val iosX64Main by getting
val iosArm64Main by getting
val iosSimulatorArm64Main by getting
val iosMain by creating {
dependsOn(commonMain)
iosX64Main.dependsOn(this)
iosArm64Main.dependsOn(this)
iosSimulatorArm64Main.dependsOn(this)
}
}
}
// Swift code — importing Kotlin framework
import shared
class IOSPlatform: Platform {
let greeting = "Hello from iOS"
func getPlatformName() -> String {
return Platform_actualKt.getPlatformName()
}
func createUser() {
let repository = UserRepository()
let greeting = repository.greet() // Calls Kotlin code
}
}
// For Kotlin Flow -> Swift
// Use KMP-NativeCoroutines or convert to callback
Output: iOS framework exported correctly. Swift code calls Kotlin functions.
Prevention
- Configure framework export in
build.gradle.ktsfor each iOS target. - Import the framework with
import shared(or yourbaseName). - Use
@ObjCNameannotations for cleaner Swift API. - Use KMP-NativeCoroutines for bridging Kotlin coroutines to Swift.
Common Mistakes with multiplatform ios
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world KOTLIN code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro