Writing Swift-Friendly Kotlin Multiplatform APIs — Part 1
*This list contains some important notes and solutions for common issues in KMP projects So I will sum up these articles into a form of points like this
[Issue Title]
? Normal kotlin implementation
? The issue in swift code
? The solution in kotlin to fix the issue
? The solution in swift side [if there]
-[Issue Title] Calling Methods Versus Sending Messages
-Normal kotlin implementation:
fun findElementInList(elem: Int, list: List<Int>): Int = list.indexOf(elem)
-The issue in swift code:
let index = ExampleKt.findElementInList(elem: 1, list: [1, 2, 3])
Swift requires parameter names to be specified explicitly when calling functions, unlike Kotlin.
--The solution in kotlin to fix the issue:
@OptIn(ExperimentalObjCName::class)
@ObjCName("find")
fun findElementInList(@ObjCName("element") elem: Int, @ObjCName("in") list:
List<Int>): Int = list.indexOf(elem)
-Using @OptIn(ExperimentalObjCName::class) and @ObjCName annotation to specify Objective-C and Swift names for symbols.
--The solution in swift side [if there]:
let index = ExampleKt.find(element: 1, in: [1, 2, 3])
Calling the function with explicit parameter names, or with external parameter name as _ to allow omission of parameter name when calling the function in Swift.