Skip to content
This repository was archived by the owner on May 3, 2022. It is now read-only.

Commit 8ff0583

Browse files
moksh-pathakNick Vidal
authored and
Nick Vidal
committed
docs: add swift guide
Signed-off-by: Moksh Pathak <[email protected]>
1 parent 6851c22 commit 8ff0583

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

docs/WebAssembly/Swift.md

+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# WebAssembly with SwiftWasm
2+
3+
1. Setting up the environment
4+
5+
First, we need to pull the docker image and run it in an interactive mode; we would be accessing the container from its bash. To do the same, run the following command.
6+
7+
```
8+
docker run --rm -it ghcr.io/swiftwasm/swift:latest /bin/bash
9+
```
10+
11+
12+
2. Code
13+
14+
To write the fibonacci code, we need to have a text editor in the container. For this demo, we would be using nano text editor. To install the same, follow the below instructions :
15+
16+
1. First, we need to run the `apt update` command in our container.
17+
2. To install nano text editor using apt, we need to run `apt install nano`
18+
19+
With our text editor now installed in the container, lets make a swift file and write the fibonacci code in it.
20+
21+
To make a new file, we would be using the `touch` command.
22+
23+
```
24+
touch fibonacci.swift
25+
```
26+
27+
To open the newly created file in nano text editor, we use this simple command.
28+
29+
```
30+
nano fibonacci.swift
31+
```
32+
33+
The fibonacci code in Swift is as follows :
34+
35+
```
36+
func fibonacci(n: Int) -> Int {
37+
var a = 0
38+
var b = 1
39+
for _ in 0..<n {
40+
let temp = a
41+
a = b
42+
b = temp + b
43+
}
44+
return a
45+
}
46+
47+
print(fibonacci(n:7))
48+
```
49+
50+
3. Compiling the code
51+
52+
To compile your Swift code to wasm, simply run:
53+
54+
```
55+
swiftc -target wasm32-unknown-wasi fibonacci.swift -o fibonacci.wasm
56+
```
57+
58+
This would generate a `fibonacci.wasm` file.
59+
60+
61+
4. Running .wasm file in Wasmtime
62+
63+
We would be using Wasmtime as our WebAssembly runtime to run our `fibonacci.wasm` file. Before we install wasmtime in our container, we would need to install `curl` command, which is a command-line tool to transfer data to or from a server. To install the `curl` command, run the following command :
64+
65+
```
66+
apt install curl
67+
```
68+
69+
With that done, lets install our WebAssembly runtime, Wasmtime with the following command.
70+
71+
```
72+
curl https://wasmtime.dev/install.sh -sSf | bash
73+
```
74+
75+
We need to open a new terminal to start using Wasmtime, but the same can be achieved simply by the following command.
76+
77+
```
78+
exec bash
79+
```
80+
81+
To run our `fibonacci.wasm` , run the following command :
82+
83+
```
84+
wasmtime fibonacci.wasm
85+
```
86+
87+

0 commit comments

Comments
 (0)