As an iOS developer coding in Swift, I find it increasingly annoying to have to coordinate the same code written in Swift with front-end developers coding in JavaScript. It would be much neater to implement common functionality in one place and then translate to JS, right?
I've started to wonder if a Swift to JS compiler was feasible? Perhaps not to share the full code, but some generic common functions at least.
I found this transpiler online: SwiftJS. Sadly, this one doesn't really cut it.
The following code:
let a = [1, 2]
print(a.count)
returns Invalid Swift code
in the demo. Which doesn't instil confidence. Never mind the more intricate bits like optionals or function overloading.
I was wondering about starting a transpiler project, but then I realised there were many pitfalls. For instance this code:
var a = [1, 2]
var b = a
b.append(3)
should make a
equal to [1, 2]
and b
equal to [1, 2, 3]
. In JavaScript, both would be [1, 2, 3]
as they're passed by reference and not by value.
Would it be at all possible to write a proper transpiler?
A transpiler between any two turing complete languages is always possible. That doesn't mean it's easy, practical, or worthwhile.
At the bare minimum, you can guarantee that a Swift to JS transpilation is possible because you can compile the Swift to x64 machine code, and use a JS disassembler/decompiler to produce JS. However, the resulting code will be really shit JS.
To make a good conversion you need to account for all the intricate best practices of one language, and what their equivalents are in the other language. That's a huge undertaking, that must be done twice (one in each direction) for any two pairs of languages you'd like to transpile. There's a reason transpilers are so uncommon, and usually crap.