https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
p

Pavel Repkin

03/01/2023, 6:32 AM
Hi! Is there a way to implement actual part of a multiplatform class in Swift? Sometimes I find it naturally to implement certain iOS tasks in Swift rather than Objective C API.
g

Gijs van Veen

03/01/2023, 8:14 AM
It's not possible. Instead you should define an interface and implement that in Swift if you want to go that route
p

Pavel Repkin

03/01/2023, 10:35 AM
@Gijs van Veen thank you. That’s the way I do it now - with the interface implementations. But this technique requires you to manually create the instances of the actual classes on iOS and Android side. expect/actual solves this.
g

Gijs van Veen

03/01/2023, 11:10 AM
Yeah it's not ideal. But Swift libraries are simply not available to Kotlin/Native so its either that or using the Objective-C api
p

Pavel Repkin

03/01/2023, 11:12 AM
Alas. It is what it is. I hope Jeteyes of Jetbrains to notice our discomfort.
l

Landry Norris

03/01/2023, 2:39 PM
I’ve seen projects that will add a
createPlatform*
method with expect/actual that will create the proper Swift class that implements your interface. This allows you to avoid creating the instance manually, while still giving the flexability of the interface. The downside, of course, is that I believe you need 2 modules to avoid circular dependencies.
p

Pavel Repkin

03/01/2023, 3:16 PM
@Landry Norris I feel confused. How do these projects create a Swift class in Kotlin code?
l

Landry Norris

03/01/2023, 3:17 PM
Any public class marked with @objc can be used in Koltin.
What you’d do if you need access to a pure swift function is create a Kotlin interface in a core module, create a Swift framework that calls the Swift method and mark it objc, then import that framework into another module. You can call your objc compatible class from Kotlin.
p

Pavel Repkin

03/01/2023, 3:20 PM
Thank you so much. I think I need to learn how to import custom Swift frameworks in KMM projects.
l

Landry Norris

03/01/2023, 3:21 PM
There’s a way to have a swift module create a Header for objc compatible parts. You just have it create that header and treat it like an objc framework.
p

Pavel Repkin

03/01/2023, 3:21 PM
Thank you!
Do you know a good tutorial on integrating Objective C framework into kmm project?
l

Landry Norris

03/01/2023, 3:22 PM
Someone created this gradle plugin that helps with importing Swift code. No idea how to link the swift module against something.
p

Pavel Repkin

03/01/2023, 3:22 PM
Thanks! 👍
l

Landry Norris

03/01/2023, 3:23 PM
If you have the objc framework, you can also use a def file with cinterop normally.
p

Pavel Repkin

03/01/2023, 3:24 PM
Thank you!
7 Views