Elon Tusk
Elon Tusk

Reputation: 141

How are Swift and Obective-C interoperable despite having different runtimes?

As I understand it, Swift and Objective-C are interoperable. A project predominantly written in Swift can use Objctive-C libraries (or even C and C++ libraries) and vice versa.

I know that Java and Kotlin can do this because they have the same runtime (JVM). But I've read that Swift has its own runtime separate from Objective-C's. So how are Swift and Objective-C interoperable?

Upvotes: 2

Views: 138

Answers (1)

Sweeper
Sweeper

Reputation: 270733

Having the same runtime isn't a necessary condition for interoperability, but it certainly makes interoperating two languages a lot easier.

Arguably, Kotlin and Java don't have the same runtime either. Kotlin has its own runtime built on top of the JDK/JVM. This is what makes suspend functions, Kotlin reflection, and other Kotlin-specific features work.

All that matters is that Kotlin's compiler can output binaries that Java's compiler can understand, and Java's compiler can output binaries that Kotlin's compiler can understand. That is, the compilers follow each other's ABI.

With both of them running on the JVM, lots of this is given "for free". Kotlin's compiler can just output a Kotlin method as a JVM method, a Kotlin class as a JVM class, calling a Java method from Kotlin generates basically the same bytecode as calling a Java method from Java, etc.

Similarly, when you call a Objective-C method in Swift, swiftc just outputs the same instructions clang would output for that method call, as if some Objective-C code had called it. If a class is marked @objc in Swift, swiftc generates Objective-C headers for that class, as if it were an Objective-C class, and so on.

In theory, Swift could be made to interoperate with Java. One can write a Swift compiler that outputs Java bytecode.


Having the same runtime isn't a sufficient condition for interoperability either. Kotlin's compiler generates synthetic members to implement some of Kotlin's language features, which are ignored by Java's compiler. Similarly, not every Swift declaration can be made visible to Objective-C (e.g. protocols with associated types), and Objective-C macros that are not just simple constants, are not visible to Swift either.

Upvotes: 0

Related Questions