Open23

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

treastrain / Tanaka Ryogatreastrain / Tanaka Ryoga

現在の自分の環境

  • 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
    
treastrain / Tanaka Ryogatreastrain / Tanaka Ryoga

1. GitHub Container Registry から Docker イメージを pull

swiftwasm/swiftwasm-dockerGitHub 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
treastrain / Tanaka Ryogatreastrain / Tanaka Ryoga

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:/#
treastrain / Tanaka Ryogatreastrain / Tanaka Ryoga

4. WASI で Swift プログラムを WebAssembly 向けにコンパイル

swiftc -target wasm32-unknown-wasi hello.swift -o hello.wasm
treastrain / Tanaka Ryogatreastrain / Tanaka Ryoga

1. swift package init

mkdir WasmConcurrencyPlayground && cd WasmConcurrencyPlayground && swift package init --type executable
treastrain / Tanaka Ryogatreastrain / Tanaka Ryoga

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!")
    }
}