Search code examples
swiftkotlinkotlin-multiplatformxcframework

Using Swift protocol default implementation in Kotlin Multiplatform


I try to use in Kotlin Multiplatform XCFramework with Swift code.

I have a protocol with extension for default implementation of this protocol

@objc protocol Greeting {
    var something: String { get }
}

extension Greeting {
    var something: String {
        return "Hello from Swift"
    }
}

And in Platform.kt I'm writing

class GreetingImpl: NSObject(), GreetingProtocol {

    override fun something(): String {
        return (this as GreetingProtocol).something() 
    }
}

actual class Platform actual constructor() {
    val object = GreetingImpl()
    val value = object.something() //Application builds but falls here
}

How can I use Swift protocol default implementation in Kotlin Multiplatform?


Solution

  • As far as I can see, there are two main problems:

    1. The extension is missing an @objc annotation. While this is a Swift-side limitation, this prevents Kotlin from providing full interoperability(Kotlin/Native supports no direct interoperability with Swift, only through Objective-C [docs]).
    2. Objective-C does not support protocol default implementation(see this related StackOverflow question).

    So, I would say there is no option to use Swift protocol default implementation in Kotlin Multiplatform.