Swift export in Kmp
Starting from version 2.1.0 we can start testing the Swift export in Kotlin. This feature allows you to export the Kotlin shared modules to Swift without the use of Objective-C. This will improve the iOS developers experience when using KMP modules.
At the moment basic support includes:
- Export multiple Gradle modules to Swift.
- Define the Swift module names.
- Flatten package structure
Enable the feature
To start testing this functionality you should enable it on gradle.properties
file:
kotlin.experimental.swift-export.enabled=true
Configuration
After adding the line above you need to add this configuration to the build.gradle.kts
file:
|
|
Next step is configuring xcode to launch the new task embedSwiftExportForXcode
instead of embedAndSignAppleFrameworkForXcode
. You can do it from xcode build phases configuration of the iosApp or from Android Studio modifying the project.pbxproj
file.
You should change this line:
shellScript = "cd \"$SRCROOT/..\"\n./gradlew :shared:embedAndSignAppleFrameworkForXcode\n";
With this one:
shellScript = "cd \"$SRCROOT/..\"\n./gradlew :shared:embedSwiftExportForXcode\n";
After this changes you should be able to launch the app from Android Studio or xcode without any problems.
Before enabling the feature
If you try to jump to the definition of a kotlin function from xcode in a swift file, you will be prompted with the Objective-C code exported from the kotlin shared module. This file is huge given the complexity of the project used for this example.
I will show you just a little piece of the 175 lines file generated from the Kotlin source code:
|
|
After enabling the feature
When you enable the feature and build the project, trying to go to the definition of a function from the Kotlin code, xcode will show you the exported Swift code.
|
|
The code above this lines is the complete file with 28 lines, a huge difference with the 175 lines from the Objective-C exported code. Also it’s important to mention the lower complexity and higher readability on the Swift example.
Conclusion
After testing this new feature, I’m really amazed with the improvement it brings to the iOS development in KMP projects. Also impressed with the difference in code between Objective-C and Swift exported codes. I’m sure this feature will improve in next versions and it will close the bridge between the native and multiplatform development experiences.
You can find the repository with the code from this example in SwiftExport, with two branches, main, where it’s the usual iOS framework configuration, and swift-export branch which has the new feature enabled.