Mappings between Kotlin and Swift
Swift export maps Kotlin declarations and types to their Swift equivalents. The table below shows how Kotlin concepts are mapped to Swift.
Kotlin | Swift |
|---|---|
| |
| |
| |
| |
| |
| |
Function | |
Variadic parameter | |
Wrapper class | |
Swift extension or static func | |
| |
| |
| |
Property | |
Initializer | |
Nested enum | |
| |
| |
| |
Swift attributes and DocC | |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| |
KDoc | DocC |
Check out our swift-export-sample project, a runnable Kotlin Multiplatform sample that features the mappings described on this page. Each section below links to the Kotlin declarations and to the Swift code that uses them.
Declarations
Classes
Final Kotlin classes that directly inherit from Any, like class Foo(), are translated to Swift classes that inherit from a special KotlinBase class:
Kotlin classes that subclass Objective-C classes are not exported.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Kotlin classes |
Interfaces
Kotlin interfaces are exported as Swift protocols. Use an existential such as any Repository when you need a value whose concrete type can vary. To implement an exported Kotlin interface in Swift, inherit from KotlinBase and conform to the protocol. Swift structs and enums cannot conform to Kotlin interfaces.
Kotlin fun interface declarations also become protocols. Swift export provides a lowercase factory that accepts a closure to create an implementation:
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Kotlin interfaces | ||
Kotlin interface implemented in Swift |
For the end-to-end pattern, see Cross-language inheritance.
Open and abstract classes
Kotlin open and abstract classes are exported as open Swift classes. You can subclass them from Swift, and overrides of Kotlin open members dispatch back to the Swift implementation. Swift does not require you to override an abstract Kotlin member: the subclass compiles, but calling the unimplemented member fails at runtime. Overriding a Kotlin member that is not open can fail at runtime, and Kotlin protected members are not accessible from Swift.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Kotlin open and abstract classes |
For the end-to-end pattern, see Cross-language inheritance.
Data classes
Kotlin data classes are exported as Swift classes. Their toString(), equals(), and hashCode() members map to description, isEqual(_:) (and Swift equality), and hash, respectively. The generated copy method requires every constructor argument; it does not provide Kotlin's default values for omitted arguments. Kotlin's componentN() functions are not exported.
See an example in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Data classes |
Objects
Objects are translated to Swift classes with a private init and static shared accessor:
See an example in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Objects |
Companion objects
Kotlin companion objects are exported as singleton objects accessible through the companion type's shared property:
Named companions use their declared name. An object can also be a subtype in a sealed hierarchy.
See an example in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Companion objects |
Type aliases
Kotlin type aliases are exported as is:
Enums
Kotlin enum class declarations are exported as regular native Swift enum types:
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Enum classes |
Sealed classes and interfaces
Sealed hierarchies defined in Kotlin are mapped to Swift enums, enabling exhaustive switch statements.
Swift export generates a sealedType() method on each sealed type. This method returns a Swift enum whose cases match the direct subclasses of the sealed hierarchy. You can nest these calls to match deeper levels of the hierarchy.
For example, declare a sealed interface with a class hierarchy in Kotlin:
On the Swift side, you can use an exhaustive switch without a default case:
Because the switch is exhaustive, the compiler warns you if a new subclass is added to the sealed hierarchy, so you can handle it immediately instead of relying on a default case for switch.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Sealed classes and interfaces |
Inner and nested classes
Kotlin nested classes are available through the enclosing Swift type, for example Outer.Nested(). Kotlin inner classes also need an instance of their enclosing class; Swift export exposes this as the outer__ initializer argument.
See an example in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Inner and nested classes |
Functions
Swift export preserves Kotlin function names and uses Kotlin parameter names as Swift argument labels. The Kotlin types map to their corresponding Swift types:
For extension functions declared outside the root package, the receiver becomes the first Swift argument. See Extensions for the root-package mapping.
Swift export does not apply Kotlin default argument values on the Swift side. You must pass every argument, including arguments with a default value: code that omits such an argument does not compile. To call a function with fewer arguments, provide a Kotlin overload. Overloads keep their Kotlin name and labels, so you may need to disambiguate a numeric literal with a Swift type cast:
Kotlin value classes are exported as wrapper classes rather than being erased to their underlying value. For example, given the following Kotlin declaration, Swift code calls the factory with a String and receives an Email wrapper:
When a Kotlin function expects an Email, pass the Email wrapper from Swift, not the raw String.
Kotlin lambda parameters are exported as @escaping Swift closures. You can pass a closure inline or use trailing-closure syntax; a function that returns a function type returns a Swift closure. Receiver lambdas receive their Kotlin receiver as the first closure parameter:
Kotlin vararg parameters map to Swift variadic parameters:
Kotlin operators map to Swift operators where supported. For example, plus is available as a + b, get as a[index], and invoke as a(). For more details on Kotlin declaration rules, see operator overloading.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Top-level functions, overloads, | ||
Function types and lambdas | ||
Lambdas with receiver | ||
Inline functions and a | ||
Operator functions | ||
Context parameters | — |
Properties
Kotlin properties are translated to Swift properties:
A Kotlin property with a private set is read-only from Swift. Top-level properties are available through their package namespace, like top-level functions.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Top-level properties | ||
Member properties, including |
Constructors
Constructors are translated to Swift initializers:
Kotlin default argument values are not applied when Swift calls an initializer. Pass every argument. A constructor marked with @Throws is exported as a throwing initializer, which you call with try.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Primary, secondary, and value class constructors | ||
Throwing constructors |
Extensions
An extension declared in the root package, or in the package selected by rootPackage, becomes a Swift extension. An extension declared in another Kotlin package is exported as a static function in that package namespace, with the receiver as its first argument. This applies to extension functions and properties, including extensions on regular Kotlin classes, on platform classes such as String, and on companion objects. Outside the root package, you call all of them through the package namespace as static functions or getters.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Extensions |
Annotations
Kotlin annotation | Swift export |
|---|---|
| Renames exported declarations; |
| Hides declarations from Swift export; references to them can become unavailable stubs. |
| Ignored; the declaration is exported under its normal name and is not refined in Swift. |
|
|
| Exports public opt-in APIs with |
| Adds Swift |
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Annotations and KDoc |
Visibility
Only public declarations are part of the exported Swift API. Kotlin internal and private declarations are not available to Swift. Kotlin protected members are also not visible from Swift, including from Swift subclasses.
Types
Primitive types and strings
Kotlin primitive types are mapped to their Swift counterparts. Kotlin Int maps to Int32, not Swift Int. Convert a Swift Int value to Int32 before passing it to a Kotlin function called from Swift. Kotlin Char maps to Unicode.UTF16.CodeUnit, not Swift Character. Unsigned Kotlin types keep their unsigned Swift counterparts.
Kotlin | Swift |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Swift and Kotlin strings are copied across the boundary. Do not rely on object identity between them. Kotlin Any maps to any _KotlinBridgeable, the bridge protocol supported by primitive, string, collection, and Kotlin object values.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Primitive types, strings, and |
Nullability
Kotlin nullable types map directly to Swift optionals. Swift export does not box nullable primitives in wrapper types: Int? is represented as the Swift optional Int32?, and a nullable protocol value can be written as (any Repo)?:
In this example, explicit Optional<Int32>.some(42) syntax shows the exact value crossing the boundary; in ordinary Swift code, you can use 42 where the optional type is inferred.
See an example in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Nullability |
Collections
Kotlin read-only collection types map to native Swift collections. Swift export copies collection values across the boundary:
Kotlin | Swift |
|---|---|
|
|
|
|
|
|
|
|
|
|
For example, List<Int> becomes [Int32]. A Map<Any, V> uses AnyHashable keys. Kotlin Array<T> and primitive arrays map to opaque ExportedKotlinPackages.kotlin.Array types that you cannot construct from Swift.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Collections, ranges, and arrays |
Generics
Swift export erases Kotlin generic type parameters. The generated Swift API does not keep the Kotlin type arguments, and you cast a generic result back to its expected Swift type. An unbounded T is represented by (any _KotlinBridgeable)?; a bounded type parameter is represented by its bound. For example, a parameter bounded by Shape accepts a Shape implementation, but Swift rejects an unrelated type.
Kotlin star projections and variance do not add Swift generic type arguments. Swift uses the erased type, and casts between variance forms do not change it.
Some generic declarations are not exported at all:
Reified functions.
F-bounded and multiple-upper-bound generic declarations.
Functions with a parameter whose type is a generic class instantiated with a concrete type, such as
Box<String>. Collections of such types as parameters can also fail the build.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Generic classes and functions | ||
Reified functions and a concrete type wrapper | ||
Non-generic wrappers for generic types |
kotlin.Nothing
The Kotlin Nothing type is translated to the Never type. Unit values map to Swift's empty tuple (), and you cannot construct a value of Nothing/Never:
See an example in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
|
Platform and cinterop types
Foundation and UIKit types keep their Swift names, such as NSDate and UIViewController, and the generated module imports the corresponding frameworks. Objective-C protocols keep their Objective-C/Swift names, for example any NSCopying.
C structs, C enums, platform type aliases such as NSTimeInterval, and POSIX or Darwin types are unavailable through Swift export.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Platform-specific |
Packages
Kotlin packages are translated to nested Swift enums to avoid name collisions:
Top-level functions and properties are static members of their package enum. Swift export does not generate FileNameKt classes. ExportedKotlinPackages provides the package namespaces; it is usually re-exported, so you can write foo.bar.callMeMaybe(). Use the fully qualified ExportedKotlinPackages name when a package name conflicts with a Swift type, module, or local variable.
When you set rootPackage = "com.example", declarations in that exact package are also available at the module level. Its subpackages are available as namespaces, for example feature.Foo.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Top-level declarations with | ||
Declarations exported from several Gradle modules |
Concurrency
Suspending functions
You can call suspending Kotlin code from Swift. Kotlin suspending functions and suspending functional types are exported as Swift's async counterparts:
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Suspending functions |
Flows
You can export kotlinx.coroutines flows as Swift's AsyncSequence:
For Flow<T>, Swift export also provides a typed any KotlinTypedFlow<T> wrapper. A lower-level API is available as well: call collect(collector:) with a Swift FlowCollector implementation whose emit method is async throws.
StateFlow<T> is exposed as a KotlinTypedStateFlow<T> with a typed .value. SharedFlow is exposed through a KotlinTypedSharedFlow wrapper with a typed replayCache. MutableStateFlow<T> exposes a readable and writable .value and compareAndSet; MutableSharedFlow exposes emit(value:) and tryEmit(value:). Swift cannot create a Kotlin flow directly. Expose a Kotlin builder that creates and returns a flow; for example, return a MutableStateFlow<String> and set its .value from Swift.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Flows, including | ||
Kotlin flow implemented in Swift |
Cancellation
Cancelling the Swift Task that calls a suspending function or collects a flow cancels the Kotlin coroutine. Kotlin suspending functions are exported as async throws, so call them with try await; cancellation is reported to Swift as CancellationError.
Collecting a flow with asAsyncSequence() starts a Kotlin Job that runs Flow.collect. Cancelling the surrounding Swift Task also cancels that collection. Swift export does not await the Kotlin Job after cancellation, so cleanup in Kotlin finally can run concurrently and continue after the Swift Task has finished:
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Cancellation of suspending functions and flows |
Coroutine dispatchers
By default, when you call a Kotlin suspending function from Swift or use the asAsyncSequence function, Kotlin creates a coroutine context that uses the Dispatchers.Default dispatcher and executes the exported code there.
To run the exported code on a different dispatcher, use the withContext() function to switch the coroutine context in Kotlin. For example:
Error handling
Functions and constructors annotated with @Throws are exported as Swift throws declarations. Call them with try in a do block. kotlin.Throwable conforms to Swift.Error, so you can catch an exported Kotlin exception by its concrete type:
Keep in mind that:
If the thrown Kotlin exception type is not exported, Swift receives it as
KotlinRuntimeSupport.KotlinError.trycalls are not necessary if a non-suspending function throws an exception, but doesn't have the@Throwsannotation. Any uncaught exception terminates the process, so try annotating every expected exception with@Throws.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Exceptions and |
Cross-language inheritance
Swift export supports cross-language inheritance. A common use case for this feature is the reverse import pattern, where you define a contract in Kotlin and provide platform-specific implementations on the Swift side. This is especially useful when you need to use pure Swift libraries that can't be directly imported into Kotlin.
To implement the pattern, declare a Kotlin interface and a function that accepts it. On the Swift side, create a class that inherits directly from the Kotlin runtime's KotlinBase class and conforms to the exported protocol. Implement the interface using a pure Swift library and pass the object back to Kotlin. For example, for the CryptoKit library:
On the Kotlin side, declare an interface and a function that accepts it:
// Kotlin interface CryptoProvider { fun hashMD5(input: String): String } fun processHash(provider: CryptoProvider, input: String): String = provider.hashMD5(input)On the Swift side, inherit from
KotlinBase, implement the interface using a pure Swift library, and pass the object back to Kotlin:// Swift import CryptoKit import Shared import KotlinRuntime final class IosCryptoProvider: KotlinBase, CryptoProvider { func hashMD5(input: String) -> String { guard let data = input.data(using: .utf8) else { return "failed" } return Insecure.MD5.hash(data: data).description } } let provider = IosCryptoProvider() // Calls the Kotlin function, which calls hashMD5() back in Swift print(processHash(provider: provider, input: "Hello, world!"))
When Kotlin receives the Swift object, it treats it like an implementation of a regular Kotlin interface, calling the Swift code directly.
See examples in the Swift export sample:
Example | Kotlin side | Swift side |
|---|---|---|
Kotlin contract |