Open23
SwiftWasm 体験記 〜Hello, world!(単一ファイル・Swift Package・Swift Concurrency)〜

swiftwasm/swift: WebAssembly support for the Swift programming language

Introduction - Swift and WebAssembly

現在の自分の環境
- macOS Monterey 12.6 (21G115)
- MacBook Pro (13-inch, M1, 2020)
- Xcode 14.0.1 (14A400)
-
% swift --version swift-driver version: 1.62.8 Apple Swift version 5.7 (swiftlang-5.7.0.127.4 clang-1400.0.29.50) Target: arm64-apple-macosx12.0

Releases · swiftwasm/swift
リリースページを見たところ、swift-wasm-5.7.1-RELEASE
はあるものの、Xcode 14.0.1 に含まれる Swift 5.7 に対応したものが無い…?(Development Snapshot はあるが)

現在の自分の環境
-
% docker --version Docker version 20.10.17, build 100c701

1. GitHub Container Registry から Docker イメージを pull
swiftwasm/swiftwasm-docker の GitHub Container Registry から、 Docker イメージを pull する。
docker pull ghcr.io/swiftwasm/swift:5.7-focal
% docker pull ghcr.io/swiftwasm/swift:5.7-focal
5.7-focal: Pulling from swiftwasm/swift
675920708c8b: Pull complete
fead0ea9c915: Pull complete
12219dd44e2e: Pull complete
4f4fb700ef54: Pull complete
Digest: sha256:6017daa088280251dceda065331ce4c7b9863718b73be573fb143dad9d81e166
Status: Downloaded newer image for ghcr.io/swiftwasm/swift:5.7-focal
ghcr.io/swiftwasm/swift:5.7-focal

2. コンテナを作成して attach
docker run --rm -it ghcr.io/swiftwasm/swift:5.7-focal /bin/bash
% docker run --rm -it ghcr.io/swiftwasm/swift:5.7-focal /bin/bash
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
root@0280b688542b:/#

hello.swift
を作成
3. echo 'print("Hello, world!")' > hello.swift

4. WASI で Swift プログラムを WebAssembly 向けにコンパイル
swiftc -target wasm32-unknown-wasi hello.swift -o hello.wasm

5. WebAssembly のランタイムを準備
今回はランタイムに Wasmer を使ってみる。
Wasmer - The Universal WebAssembly Runtime

.wasm
を WebAssembly のランタイムで実行
6. 生成された wasmer hello.wasm

Hello, world!
単一ファイル版
ここまでできたよ 
Swift Package からビルドしてみる
Using Swift Package Manager - Swift and WebAssembly

swift package init
1. mkdir hello && cd hello && swift package init --type executable

--triple
をつけて swift build
2. swift build --triple wasm32-unknown-wasi

.wasm
を WebAssembly のランタイムで実行
3. 生成された wasmer .build/debug/hello.wasm

Hello, world!
Swift Package 版
ここまでできたよ 
Swift Concurrency を使ってみる
Concurrency - Swift and WebAssembly

swift package init
1. mkdir WasmConcurrencyPlayground && cd WasmConcurrencyPlayground && swift package init --type executable

2. main なファイルを編集
Sources/WasmConcurrencyPlayground/WasmConcurrencyPlayground.swift
@main
public struct WasmConcurrencyPlayground {
public static func main() async throws {
print("Hello,")
try await Task.sleep(nanoseconds: 1_000_000_000)
print("happy")
try await Task.sleep(nanoseconds: 1_000_000_000)
print("world!")
}
}

--triple
をつけて swift build
3. swift build --triple wasm32-unknown-wasi

.wasm
を WebAssembly のランタイムで実行
4. 生成された wasmer .build/debug/WasmConcurrencyPlayground.wasm
