When we publish a Kotlin Multiplatform library, we sometimes want to ship some Swift with it: code that calls the library's Kotlin and comes packaged with it. A ready-to-use API, a wrapper, boilerplate that every iOS app would end up writing.
That's the case as soon as a library exposes ViewModels to SwiftUI: Swift can't collect a Kotlin Flow, and it can't clear a ViewModel either. That layer of Swift glue code usually ships as a Swift package, or as code to copy from the docs.
It can also ship as a skill: the Swift files, the rules to install them, and an agent that adapts them to the consumer's project.
The examples come from a library we'll tell you about soon. Types are renamed and the code is simplified.

What Swift doesn't see of a Kotlin ViewModel
We start from a screen described in common Kotlin: a contract, and a ViewModel that implements it.
interface Counter : Screen<Model, Intent, Signal> {
data class Model(val count: Int) : Screen.Model
sealed interface Intent : Screen.Intent {
data object Increment : Intent
}
sealed interface Signal : Screen.Signal {
data object Saved : Signal
data class Error(val message: String) : Signal
}
}
class CounterVM : Counter, ScreenViewModel<Model, Intent, Signal>(
firstModel = Model(count = 0),
) {
// modelFlow: StateFlow<Model> the state the view renders
// signalFlow: Flow<Signal> one-off events
// post(intent) what the view sends up
}Kotlin/Native exports this code to Swift through an Objective-C header. Four things get lost on the way.
- Flows. Swift can't collect a
Flow:modelFlowandsignalFloware unusable as they are. - Lifecycle. Swift can't clear a ViewModel, and SwiftUI re-creates its views all the time. Something has to create the VM once and clear it when the view goes away.
- Generics. A generic interface becomes a protocol with no type parameters. The view can then post another screen's intent: the code compiles, and fails at runtime on the Kotlin side. The bounds of type parameters are dropped too.
- Sealed hierarchies. Each case of a
sealed interfacearrives as a class of its own. Swift can't check that aswitchon a signal is exhaustive.
Names change too:
| Kotlin | Swift |
|---|---|
Counter.Model | CounterModel |
Counter.Intent.Increment, a data object | CounterIntentIncrement.shared |
Counter.Signal.Error(message) | CounterSignalError(message:) |
Int, Long | Int32, Int64 |
a property named description | description_ |
Bridging these gaps takes code that adds nothing to the app: wrappers, conversions, lifecycle management.
We could have built on SKIE or KMP-NativeCoroutines. We didn't: a library that adopts them forces them on every consumer. And for interop, we'd rather have plain code than a compiler plugin.
An interop layer in two halves
The library bridges these gaps in two places: one part in Kotlin, published in its artifact, and one part in Swift.
Kotlin side: a host and callbacks
On iOS, the library's code (iosMain) turns flows into callbacks, a shape Swift knows how to call.
// iosMain, in the library's artifact
class ScreenHost<Model : Screen.Model, Intent : Screen.Intent, Signal : Screen.Signal>(
newVM: () -> ScreenViewModel<Model, Intent, Signal>,
) {
private val store = ViewModelStore()
private val vm by lazy { /* creates the VM in `store`, on first access */ }
val model: Model get() = vm.modelFlow.value
val scope: ScreenViewScope<Intent, Signal> get() = vm
fun observeModels(onModel: (Model) -> Unit): ScreenCancellable =
ScreenCancellable(vm.viewModelScope.launch {
vm.modelFlow.collect { onModel(it) }
})
fun clear() = store.clear()
}The host is a class, not an interface: that way the Objective-C export keeps its type parameters, and Swift sees a typed model. The VM lives in a ViewModelStore owned by the host, until clear().
Signals go through a second function:
fun <Signal : Screen.Signal> ScreenViewScope<*, Signal>.collectSignals(
onSignal: (signal: Signal, done: () -> Unit) -> Unit,
): ScreenCancellable {
val job = parentScope.launch(Dispatchers.Main.immediate) { // the VM's viewModelScope
signalFlow.collect { signal ->
suspendCancellableCoroutine { continuation ->
onSignal(signal) {
if (continuation.isActive) continuation.resume(Unit)
}
}
}
}
return ScreenCancellable(job)
}Kotlin doesn't hand over the next signal until Swift has called done. Handling stays sequential, as it would in a coroutine.
Swift side: three files
Three Swift files, about 300 lines with comments, wrap that host. The first gives SwiftUI an observable object and a view container.
import Observation
import Shared // ← the name of the app's Kotlin framework
import SwiftUI
@MainActor
fileprivate final class ScreenState<Model: ScreenModel, Intent: ScreenIntent, Signal: ScreenSignal>: Observable {
private let registrar = ObservationRegistrar()
private let host: ScreenHost<Model, Intent, Signal>
private var current: Model?
private var observation: ScreenCancellable?
init(newVM: @escaping () -> ScreenViewModel<Model, Intent, Signal>) {
host = ScreenHost(newVM: newVM)
}
isolated deinit {
observation?.cancel()
host.clear()
}
var model: Model {
registrar.access(self, keyPath: \.model)
if let current { return current }
let first = host.model
current = first
observation = host.observeModels { [weak self] model in
guard let self, model !== self.current else { return }
self.registrar.withMutation(of: self, keyPath: \.model) {
self.current = model
}
}
return first
}
var scope: ScreenScope<Intent, Signal> { ScreenScope(host.scope) }
}
struct ScreenContainer<Model: ScreenModel, Intent: ScreenIntent, Signal: ScreenSignal, Content: View>: View {
@State private var state: ScreenState<Model, Intent, Signal>
private let content: (Model, ScreenScope<Intent, Signal>) -> Content
init(
newVM: @escaping () -> ScreenViewModel<Model, Intent, Signal>,
@ViewBuilder content: @escaping (Model, ScreenScope<Intent, Signal>) -> Content
) {
_state = State(initialValue: ScreenState(newVM: newVM))
self.content = content
}
var body: some View { content(state.model, state.scope) }
}The VM is created on the first read of model, not in init. SwiftUI evaluates the initial value of a @State every time the view is re-created and keeps only the first one: the others never read model, so they never create a VM. isolated deinit runs the cleanup on the main thread, whichever thread releases the last reference.
The second file puts back the types the export erased:
struct ScreenScope<Intent: ScreenIntent, Signal: ScreenSignal> {
let base: any ScreenViewScope // the exported protocol, with no type parameters
init(_ base: any ScreenViewScope) { self.base = base }
func post(_ intent: Intent) {
base.post(intent: intent)
}
static var empty: Self { Self(EmptyScreen<Intent, Signal>()) }
}post now only takes the screen's own intent: the error is back at compile time. .empty is there for previews.
The third file is a view modifier for signals. It collects in a .task, so for as long as the view is on screen, and bridges the Kotlin callback through an AsyncStream:
extension View {
func onScreenSignal<Intent: ScreenIntent, Signal: ScreenSignal>(
of scope: ScreenScope<Intent, Signal>,
perform: @escaping @MainActor (Signal) async -> Void
) -> some View
}
// At the heart of the modifier:
let (pending, continuation) = AsyncStream.makeStream(of: PendingSignal.self)
let collection = ScreenSignalsKt.collectSignals(scope.base) { signal, done in
continuation.yield(PendingSignal(signal: signal, done: done))
}
defer { collection.cancel() }
for await next in pending {
guard let signal = next.signal as? Signal else {
preconditionFailure("this scope wraps the scope of another screen")
}
await perform(signal)
if Task.isCancelled { break }
next.done()
}These three files rely on nothing but the Objective-C export of Kotlin/Native: no third-party tool.
What a Swift package would force on you
Each of the three files starts with the same line:
import Shared // ← Replace with the name of your Kotlin framework.
ScreenHost and ScreenViewModel don't live in a binary shipped by the library. They live in the consumer's Kotlin framework, the one their Gradle module builds, under the name they picked:
target.binaries.framework {
baseName = "KosiCore" // the consumer's choice
}A Swift package would have to write that import ahead of time. So it would force the framework's name on all its consumers.
That left two options: document the code to copy, or let each team rewrite its own Swift layer.
The package dictates the framework's name. Copying and rewriting leave all the work to the consumer. The skill hands that work to an agent, with rules.
The skill: files, rules, templates
A skill is a folder of instructions that a coding agent loads when the task calls for it. The library's skill lives in its repository, next to the code:
skills/screens/
├── SKILL.md # when to trigger, API cheat-sheet, procedures
├── references/
│ ├── good-practices.md
│ ├── bad-practices.md # review checklist
│ └── swiftui.md # install steps, Kotlin → Swift names, limits
├── swift/ # the three files to copy
│ ├── ScreenContainer.swift
│ ├── ScreenScope.swift
│ └── View+onScreenSignal.swift
└── templates/
├── XxxContract.kt.template
├── XxxVM.kt.template
├── Xxx.kt.template # Compose view
└── Xxx.swift.template # SwiftUI viewIt covers four jobs: installing the Swift files, configuring the framework's Gradle build, creating a screen, and reviewing code.
The install procedure is written for the agent, step by step. An abridged excerpt from references/swiftui.md:
## Installing the helpers
Do these steps in order, and stop where a step says so.
1. Find the framework: the Gradle module whose `binaries.framework`,
`XCFramework("…")` or `cocoapods { framework { … } }` builds the
framework the Xcode app links. Note its `baseName`.
Several candidates: ask.
2. Export the library: an `api` dependency, passed to `export`.
Never touch a version the user pinned.
3. Check the deployment target and the toolchain: iOS 17 or more,
Swift 6.2 or more. Below either: stop and tell the user.
Do not raise the target on your own.
4. Choose the destination: the directory of the app's other Swift files.
5. Copy the files of `swift/`, and change `import Shared` to
`import <baseName>`. Never overwrite an existing file: ask first.
6. Report the files created, the Gradle lines added, and what the
user still has to do.The rules say what to read in the consumer's project, and where to stop. Two candidate frameworks, a version that's too old, a file that's already there: in all three cases, the agent asks or stops. It doesn't guess.
The screen template has just two variables, {{Name}} and {{Framework}}:
import {{Framework}}
import SwiftUI
struct {{Name}}Screen: View {
var body: some View {
ScreenContainer(newVM: { {{Name}}VM(/* … */) }) { model, scope in
{{Name}}Content(model: model, scope: scope)
}
}
}
typealias {{Name}}Scope = ScreenScope<{{Name}}Intent, {{Name}}Signal>
struct {{Name}}Content: View {
let model: {{Name}}Model
let scope: {{Name}}Scope
var body: some View {
// TODO: render `model`, call `scope.post(…)`
Text("{{Name}}")
.onScreenSignal(of: scope) { signal in
switch signal {
// TODO: one branch per Signal
default:
break
}
}
}
}Those swift/ files aren't samples. The library's SwiftUI demo app compiles them straight from the repository, and CI builds it with xcodebuild. So the agent copies exactly the code that CI compiles.
On the consumer's side
Take an iOS app whose Kotlin framework is called KosiCore. The request to the agent fits in one sentence: install the library's SwiftUI helpers.
The agent reads the baseName, then edits the Gradle module that builds the framework:
kotlin {
listOf(iosArm64(), iosSimulatorArm64()).forEach { target ->
target.binaries.framework {
baseName = "KosiCore"
+ export(libs.screens.core)
}
}
sourceSets {
commonMain.dependencies {
- implementation(libs.screens.core)
+ api(libs.screens.core)
}
}
}Without export, the library's declarations never reach the framework header: Swift couldn't name ScreenViewModel or ScreenHost. An exported module has to be an api dependency. The module that holds the contracts and the ViewModels is exported the same way, if it's a separate one.
Next, the agent checks the deployment target (IPHONEOS_DEPLOYMENT_TARGET) and the toolchain. iOS 17 is required for Observation, Swift 6.2 (Xcode 26) for isolated deinit. The guard also exists without an agent, in the file itself:
#if !compiler(>=6.2)
#error("The helpers for SwiftUI need a Swift 6.2 toolchain (Xcode 26), for `isolated deinit`")
#endifIt then copies the three files into the app's Swift sources folder, with a single line changed in each:
- import Shared // ← Replace with the name of your Kotlin framework. + import KosiCore
In an Xcode project with file-system-synchronized groups, the default since Xcode 16, copying is enough. In a classic project, the files also have to be added to the target: the agent says so, and only edits the .pbxproj if the user agrees.
Second request: create the SwiftUI screen for the Counter contract. The agent fills in the template and lists every TODO it leaves behind. Once those are filled in:
import KosiCore
import SwiftUI
struct CounterScreen: View {
var body: some View {
ScreenContainer(newVM: { CounterVM() }) { model, scope in
CounterContent(model: model, scope: scope)
}
}
}
typealias CounterScope = ScreenScope<CounterIntent, CounterSignal>
struct CounterContent: View {
let model: CounterModel
let scope: CounterScope
@State private var message: String?
var body: some View {
Button("Count: \(model.count)") {
scope.post(CounterIntentIncrement.shared)
}
.onScreenSignal(of: scope) { signal in
switch signal {
case is CounterSignalSaved: message = "Saved"
case let error as CounterSignalError: message = error.message
default: break
}
}
}
}
#Preview {
CounterContent(model: CounterModel(count: 3), scope: .empty)
}CounterContent knows only a model and a scope, never the ViewModel. That's what makes the preview on .empty possible.
The skill doesn't replace the interop layer: it changes how you ship it. The Swift files are still the author's, and an agent installs them to fit the consumer's project. Without an agent, you copy them by hand.
What the library ships is the install rules. The framework's name stays the consumer's.
The library we used as an example will be out soon, with its skill in the same repository. Stay tuned ;)
Join the conversation:
A KMP library exposing ViewModels to SwiftUI needs Swift glue code. A Swift package would hardcode `import Shared` and force that name on every consumer. We ship ours as an agent skill: it copies the Swift files and rewrites the import. kodein-koders.com/en/blog/kotl... #Kotlin #KMP #Swift
— kodein-koders.bsky.social (@kodein-koders.bsky.social) 9:00 PM · Dec 1, 2026
[image or embed]
These articles might interest you
Tutorials, lessons learned and best practices around KOSI and the Kotlin ecosystem, from the people who maintain the libraries.
23/11/2026
Harness engineering: owning what our agents produce – part 1
Guides aren't enough to trust an agent's code. A first field report on the harness built around a real product: verifications that actually run, tests seen failing, gates. What worked, what failed, and what remains to be proven.
Read more
17/11/2026
Inara has no magic: read the code it writes
In most DI frameworks, a module is an anonymous bag of bindings, and dependencies are looked up by type. Inara gives modules an identity. Let's open the hood and read the code it generates: there is no trick, only plain Kotlin you can Cmd+click through.
Read more
09/11/2026
LARPing enthusiasm: the ghost of disengagement
I can hand the work to AI, but not my judgment or my product sense. A story of sliding into disengagement, and of a comeback still in progress.
Read more
02/11/2026
Inara: Inject your dependencies at compile time
I created Kodein, yet I now believe it is detrimental to the Kotlin Multiplatform ecosystem. Meet Inara, a Kotlin Symbol Processor that resolves your dependencies at compile time, and learn why we are sunsetting Kodein.
Read more
26/10/2026
Agentic coding has killed cross-platform frameworks!
Agents made it cheap to write native code twice, so is cross-platform dead? Not quite: what changed is the question. Share what must be identical, and check it once.
Read more
19/10/2026
LARPing enthusiasm: the AI creativity frenzy
AI lets me build in weeks what once took years, and it feels like a drug. Am I really creating, or just LARPing enthusiasm? A personal reflection on agency, will and shared code.
Read more