Tugulab Blog.

Get Started With Swift for WebAssembly on macOS With SwiftWasm

Get to know SwiftWasm
author avatar

clacla

A group of brave souls behind SwiftWasm are working on adding WebAssembly as a compilation target for the Swift programming language. It’s a work in progress, so it’s not fully ready yet. But we are already able to get Swift code executed in a Wasm runtime (e.g. the browser)!

Let’s set up SwiftWasm on the latest macOS. Then let’s attempt to create our first Swift-based app!

Install Swift Language With Wasm Support

The Wasm support is not yet in the official Swift repository. Therefore, we have to install a snapshot of the language with experimental support.

Download and install the lastest macOS version of SwiftWasm (5.3 at time of writing) for macOS from the project GitHub.

To be able to use the SwiftWasm toolchain from the command line:

export PATH=/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin:"${PATH}"

And to test it has been properly setup:

swift --version

Test SwiftWasm

Create a HelloWorld Swift file:

echo 'print("Hello, world!")' > hello.swift

Compile the Swift source code to Wasm bytecode:

swiftc -target wasm32-unknown-wasi hello.swift -o hello.wasm

Run the Output

To run the code from the command line, you can use wasmer (a Wasm runtime).

Install it:

curl https://get.wasmer.io -sSfL | sh

Execute your Wasm code:

wasmer hello.wasm

Make a Swift Package With SwiftPM

We can leverage SwiftPM to create a package that will then be compiled to Wasm.

It’s simple. Let’s create a package named testpack and then just compile and execute it:

mkdir testpack && cd testpackswift package init --type executable

Let’s build it:

swift build --triple wasm32-unknown-wasi

Execute it:

wasmer .build/debug/testpack

Next Up, Create a Web App With SwiftWasm

We just barely set up the entire thing and executed a mere Hello World. Now let’s make our first ReactJS- and SwiftUI-inspired web app with Swift!