skip to content

How do you compile a Swift validation module to WebAssembly with the swift.org Wasm SDK, and when do you choose its embedded variant?

level: middleimportance: nice to knowfreq 12%

answer

  1. a Swift SDK, not an Xcode target
  2. WASI as the system interface
  3. two SDK IDs in one bundle
  4. binary size drives the choice

basics

~10 s

Install the Wasm Swift SDK matching your swift.org toolchain with swift sdk install, then build with swift build --swift-sdk <version>_wasm; the _wasm-embedded SDK uses Embedded Swift, producing far smaller binaries from a language subset.

solid answer

~40 s

Since Swift 6.2, swift.org distributes Swift SDKs for WebAssembly, and with 6.4 they are on the Install page. Install a toolchain with swiftly (required on macOS even with the latest Xcode), then `swift sdk install <url> --checksum <sum>` for the matching version. `swift sdk list` shows two IDs: `<version>_wasm` supports all of Swift, `<version>_wasm-embedded` the Embedded Swift subset. `swift build --swift-sdk <version>_wasm` produces a `.wasm` module targeting WASI; `#if os(WASI)` selects WASI-only code and the C library module is `WASILibc`. Pick the embedded SDK when the module is downloaded by browsers and size matters: it is orders of magnitude smaller, at the cost of language features such as `weak` references and casts to protocol types. Windows hosts cannot cross-compile with Swift SDKs yet, and threads need the separate `wasip1-threads` triple.

code

swift · 26 lines
swift
enum FieldError: Error, Equatable {
    case empty
    case tooLong(limit: Int)
}

func validateUsername(_ name: String) throws(FieldError) {
    if name.isEmpty { throw .empty }
    if name.utf8.count > 32 { throw .tooLong(limit: 32) }
}

@main
struct ValidatorMain {
    static func main() {
        #if os(WASI)
        let host = "WASI"
        #else
        let host = "native"
        #endif
        do {
            try validateUsername("swift-dev")
            print("valid on", host)
        } catch {
            print("invalid on", host, error)
        }
    }
}

go deeper

for a junior

Recall that Swift compiles to WebAssembly with a Swift SDK from swift.org, used through swift build --swift-sdk.

for a middle

Explain the steps: matching toolchain via swiftly, swift sdk install with a checksum, the two SDK IDs, and os(WASI) for WASI-only code.

for a senior

Judge when the embedded SDK is worth its restrictions, keep shared validation code free of weak references and protocol casts, and know the threading and dynamic-linking limits.

for a principal

Weigh one Swift source of truth for rules on app and web against the cost of a second toolchain pipeline and a language subset the web build imposes.

## What the Wasm SDK is **WebAssembly (Wasm)** is a portable virtual instruction set run by browsers and stand-alone runtimes. Swift targets it through **WASI**, the WebAssembly System Interface, which gives Wasm programs a standard way to reach files, clocks and other system services; that is what made porting Swift's core libraries practical. The target triple is `wasm32-unknown-wasip1`. Support started as a community project. **Since Swift 6.2** swift.org distributes official **Swift SDKs for Wasm**: artifact bundles in the cross-compilation format of SE-0387 that `swift build` uses through `--swift-sdk`. In Swift 6.4 the Wasm SDK is offered directly on swift.org's Install page. ## Building a validation module 1. Install swiftly, then a toolchain with `swiftly install <release>` and select it with `swiftly use <release>`. On macOS this is needed even with the newest Xcode: Swift SDKs must be paired with a swift.org toolchain. 2. Install the Wasm SDK for **exactly** that toolchain version: `swift sdk install <url> --checksum <checksum>`. 3. Run `swift sdk list` and note the two IDs. 4. Build: `swift build --swift-sdk <version>_wasm`, which links `<Product>.wasm`. 5. Run it locally with `swift run --swift-sdk <version>_wasm`; toolchains that include the **WasmKit** runtime let `swift run` delegate execution to it. 6. After every toolchain change, install the matching SDK again. Editors pick the SDK up from `.sourcekit-lsp/config.json` (`"swiftPM": {"swiftSDK": "<id>"}`). ## Two SDKs in one bundle | SDK ID | Language | Typical use | |---|---|---| | `<version>_wasm` | all of Swift, with the standard runtime | WASI tools, servers, larger browser modules | | `<version>_wasm-embedded` | the experimental **Embedded Swift** subset | browser modules where download size dominates | **Embedded Swift** compiles without the Swift runtime and specializes every generic, which the swift.org guide says makes Wasm binaries "multiple orders of magnitude smaller". In exchange some features are unavailable: `weak` and `unowned` references, dynamic casts to protocol-involving types, and generic calls the compiler cannot specialize. Code written for the full SDK may need changes before it builds embedded, so choose early. Because both IDs come from one bundle, a team can build the full variant first, measure the downloaded module, and switch to the embedded ID only if the size is unacceptable. Before switching, compile the module natively with `-Wwarning EmbeddedRestrictions`: every construct the embedded build does not support shows up as a warning, so the cost of switching is known before anyone changes the build. ## Platform checks inside the code - `#if os(WASI)` is true when building for the WASI target; `#if arch(wasm32)` tests the architecture. - The C library module is `WASILibc`, not `Glibc` or `Darwin`; swift-foundation's sources use a `canImport` chain that ends in `os(WASI)` for exactly this. - Foundation exists for WASI, and Swift 6.4 improved `FileManager` there, but a browser host has no real file system, so keep a validation module free of I/O and pass data in. ## Limits to know - **wasm64** is not supported by WASI yet. - **Threads**: a preview of multi-threading exists for the `wasm32-unknown-wasip1-threads` triple, not plain `wasm32-unknown-wasip1`. - **Dynamic linking** is not specified for the `wasip1` triples, so everything is linked into one module. - **Windows hosts** cannot cross-compile with Swift SDKs yet. - **Calling JavaScript** from the browser goes through a bridging library such as JavaScriptKit; its 6.4-era bridging is much faster, but its API is outside the language. ## Setting up an editor 1. In VS Code, run **Swift: Select Toolchain…** and choose the toolchain installed with swiftly; save it in the workspace settings. 2. Create `.sourcekit-lsp/config.json` with `{"swiftPM": {"swiftSDK": "<id>"}}`, using the exact ID from `swift sdk list` (the `-embedded` one when building Embedded). 3. Reload the window so code completion and diagnostics follow the Wasm target, including `#if os(WASI)` branches. Other editors with Swift language-server support use the same `.sourcekit-lsp/config.json` file. ## Why a validation module is the classic case Rules such as "username non-empty and at most 32 UTF-8 bytes" often exist twice, in the app and in the web front end, and drift. Compiling the Swift rules once for the iOS app and once to Wasm keeps one source of truth. Prefer **typed throws** (`throws(FieldError)`) in such a module: it carries no existential box, and it was the only form of throwing that Embedded Swift accepted before 6.4.

  • The module builds with the _wasm SDK but fails with _wasm-embedded. Where do you look first?
    At features Embedded Swift leaves out: `weak` or `unowned` references, casts like `as? SomeProtocol`, non-final generic methods in classes, and generic methods called on `any P` values. Compiling the module natively with `-Wwarning EmbeddedRestrictions` lists each one as a warning without needing the Wasm SDK, so you can fix them one by one.
  • Why does the guide require a swiftly-installed toolchain on macOS even when Xcode is current?
    A Swift SDK supplies the target's libraries and sysroot; the compiler comes from the toolchain, and the two must be the exact same version. The SDKs are built against swift.org toolchains, so you install the matching one with swiftly and select it with `swiftly use` before building.

  • Says you build Swift for Wasm by adding a target in Xcode.
  • Believes the _wasm-embedded SDK supports every Swift feature, only smaller.
  • Uses #if os(Linux) to detect a WASI build.
  • Expects a Wasm SDK from an older toolchain to work with a newer one.
  • Assumes multi-threading works on the plain wasm32-unknown-wasip1 triple.

Assumes Swift 6.4; swift.org has distributed Swift SDKs for WebAssembly since Swift 6.2, and 6.4 offers them from the Install page.