Get Started With Swift for WebAssembly on macOS With SwiftWasm
Installing the experimental Swift snapshot with WebAssembly support on macOS, then getting the first Swift code running inside a Wasm runtime.
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!
Read next
Create a React and SwiftUI-Inspired Web App With Swift for WebAssembly on MacOS With SwiftWasm
Building a web UI in SwiftUI-inspired syntax with Tokamak, compiled to WebAssembly by SwiftWasm — the toolchain, the project setup and the first app.
Expose Init Parameters and Dependencies in Swift and iOS Please
Store init parameters and dependencies as properties at the entity's own access level. It costs nothing, and it buys transparency, scale and testability.
Introducing Swift Action Delegate pattern Part 2
Part two of the Action Delegate pattern: dropping the untyped Any sender and carrying it in the DelegateAction payload instead, so no casting is needed.