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 swiftenv

To be able to manage multiple versions of the Swift language on the same machine, you need the swiftenv CLI tool. The suggested way to install it on macOS is via Homebrew (details):

brew install kylef/formulae/swiftenv

To add autocompletion in your terminal, add the following in your shell configurations:

// On Bash
echo 'if which swiftenv > /dev/null; then eval "$(swiftenv init -)"; fi' >> ~/.bash_profile

// On Zsh
echo 'if which swiftenv > /dev/null; then eval "$(swiftenv init -)"; fi' >> ~/.zshrc
// On Fish
echo 'if which swiftenv > /dev/null; status --is-interactive; and source (swiftenv init -|psub); end' >> ~/.config/fish/config.fish

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 from the SwiftWasm forked repository:

swiftenv install https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.3-SNAPSHOT-2020-10-06-a/swift-wasm-5.3-SNAPSHOT-2020-10-06-a-macos-x86_64.tar.gz

If you want, you can install a newer snapshot. Check out the list on GitHub. Install the one prefixed swift-wasm-5.3-SNAPSHOT.

Test SwiftWasm

Create a HelloWorld Swift file:

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

Compile the Swift source code to Wasm bytecode:

TOOLCHAIN_PATH=$(dirname $(swiftenv which swiftc))/../

swiftc \
    -target wasm32-unknown-wasi \
    -sdk $TOOLCHAIN_PATH/share/wasi-sysroot \
    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

#programming #swift #mac #webassembly #wasm

Get Started With Swift for WebAssembly on macOS With SwiftWasm
3.20 GEEK