Running Swift code on Android
Wednesday October 14, 2015

Apple's Swift has been available for over a year now, and Apple has promised it will be made available under an Open-Source license by the end of 2015.

That's great, but can I run Swift code on an Android device today?

The Swift Compiler

Given they were both designed by the awesome Chris Lattner, it is not a surprise to discover that Swift's compiler is built on top of LLVM. LLVM is a compiler infrastructure that leverages the very interesting concept of a retargetable compiler.

That modular design is very smart since it allows for high code reuse (sharing optimizations and backends among frontends). There are some excellent resources on the net if you want to know more about LLVM.

Targetting a different machine

At that point, you're likely wondering:

But wait, if LLVM is so modular, couldn't we use a different backend and generate binary code for something that is not OS X or iOS? Android maybe?

Well, turns out you can! Let's see how.

Building Swift code manually

Of course Xcode won't let you just point'n'click your way through this. So let's start by compiling and linking a simple Swift "Hello world" manually:

// hello.swiftprint("Hello, world!");

Building the object file it isn't very complicated:

$ $SDK/usr/bin/swiftc -emit-object hello.swift

Let's have a look at what's inside hello.o, the object file we just compiled:

Ha, that's interesting! So apparently Swift mangles symbols kind of like C++. Indeed, the print function wasn't resolved to a _print symbol but to a much more convoluted __TFSs5printFTGSaP__9separatorSS10terminatorSS_T_ list of symbols.

There's also a bunch of other symbols required too, that seem to deal with string conversion and memory handling.

Anyway, all those symbols are defined in libswiftCore.dylib, which is somewhere in the $SDK. Let's give that info to the linker: