Tugulab Blog.

Create a React and SwiftUI-Inspired Web App With Swift for WebAssembly on MacOS With SwiftWasm

SwiftWasm is experimental but that doesn’t mean we can’t have some fun!
author avatar

clacla

The first step is to set up your macOS machine to use the experimental SwiftWasm (WebAssembly compilation target). Here is a guide on how to do it.

Install the Development Tools

We are going to use Tokamak to create a web UI using the SwiftUI-inspired syntax. The long-term goal is to create web UIs just like we do for the Apple ecosystem.

But first, let’s install some development tools to simplify the process:

brew install swiftwasm/tap/carton

Create a Tokamak-Based Project

mkdir TokamakApp && cd TokamakAppcarton init --template tokamak

Now let’s start the development server with live reloading:

carton dev

Open in your favourite browser http://127.0.0.1:8080. Now every time you edit the code in the project, carton will reload the browser tab. Very JS-development style. Convenient.

Reality Check

Now the theory goes that we can write the app UI with Tokamak as if it was SwiftUI code. The reality is that Tokamak is far from finished, so not all SwiftUI entities are fully implemented yet.

Using a JavaScript Wrapper to Create Your Website

What we can do is go down one level and create DOM elements with the support of JavaScript. We can use DOMKit. It is a medium-level Swift wrapper around the browser’s DOM.

Or we can go down two levels, using JavaScriptKit. It is a low-level Swift wrapper around the JavaScript API that we use to interface with the DOM directly.

You can find more examples here.

Importing and Exporting Functions

Until the Swift web tooling is really solid and features are complete, we will probably still have to develop some part of a web app with JS-based frameworks. Therefore, the need arises to import some JS functions into our Swift app. But probably it will be more useful to export some Swift functions to the JS app, like exporting a really performing and computing intense Swift function for image manipulation for the JS interface.

Conclusion

Swift for WebAssembly and for the web in general is clearly immature and incomplete, but it’s a very encouraging start. I really hope that it becomes a real option for full-stack Swift web developers in the not-too-distant future.