Run a Swift Hello World server in less than 5 minutes

Michele Rexha
Phi Skills
Published in
6 min readApr 23, 2020
Swift

This article is an informal introduction to Swift. It focuses on what makes Swift appealing and show how to easily start using it server-side.
Future articles will cover more in depth Swift use cases as well as its syntax.

A brief story of Swift

Swift was created by Apple in 2014 setting it to become the dominant language for iOS development. Being backed up by one of the most influential tech companies in the world is quite a thing. In addition, farsightedly, Apple open-sourced Swift in 2015. Not surprisingly, it evolved to encompass uses ranging from systems programming to mobile and desktop apps, scaling up to cloud services as well as Machine Learning.

Swift the language

Swift is a general-purpose, multi-paradigm, compiled and high-performance system programming language. Swift philosophy gravitates around the following principles:

  • Safe. Its syntax encourages you to write clean and consistent code and is safe by default. Though, you can always opt for the unsafe option to make parts of your code run faster.
  • Fast. Swift is intended as a replacement for C-based languages (C, C++, and Objective-C). Not surprisingly, it is being adopted for Deep Learning and Differential Computing.
  • Expressive. The official Swift documentation states that “(Swift) syntax that is a joy to use”, I can only agree with that. It’s truly a pleasure to code with such elegant syntax.

Enough with the Swift propaganda, let’s talk about why I got hung up on Swift in the first place.

Swift and AI

I came across Swift while following the Fastai Deep Learning course. I was astonished to find that the two of the fourteen lectures are about Swift: that’s about 15% of the content 😮! In fact, a new Fastai implementation with Swift might soon see the light.

Google is also in the game with Swift for TensorFlow.

Swift for TensorFlow is a next-generation platform for machine learning, incorporating the latest research across machine learning, compilers, differentiable programming, systems design, and beyond. This is an early-stage project: it is not feature-complete nor production-ready, but it is ready for pioneers to try in projects, give feedback, and help shape the future!

Why suddenly Swift, a seemingly iOS/macOS orientated language is getting so much traction in machine learning?

Deep learning is computationally expensive, passing huge data sets through long chains of tensor operations can be quite challenging. In fact, Python has a limit in terms of how far it can perform these calculations quickly.

Any deep learning practitioner using a language other than Python is giving up a vast ecosystem of interconnected libraries. The problem is that Python is neither designed to be fast nor to be safe. Instead, it is designed to be easy and flexible. As a matter of fact, performance problems have been reduced by using libraries written in other languages such as C and C++ (Numpy, Pytorch, Tensorflow…). To make Python safer, a mechanism of optional type annotations has been introduced. These are not powerful enough though and only mitigate the problem. The C and C++ libraries introduce also another layer of complexity: any deep learning practitioner will have a hard time debugging Python code that uses these libraries.

Swift is designed to be almost as fast as C and C++, safe and expressive. It clearly has all the ingredients to reach the next stage of adoption.
In particular, we are already able to really easily run Swift server-side. Let’s see how.

Server-side Swift

If we want to be able to deploy ML models at scale in the near future, we must start by deploying servers with Swift.

When it comes to server-side Swift, there are a few solutions but not too many yet. The two I took into considerations are Vapor and Kitura. The former started as an independent open-source project whereas the latter started as an internal project at IBM which controlled it and sponsored it until its inception. Vapor syntax is closer to Swift language and to functional programming style. So I decided to use it. You can read more about the difference between the two here.

To be able to deploy Swift services at ease, the best solution is to use Docker. For those unfamiliars, Docker can run software packages in self-contained isolated environments called containers. These containers bundle their own tools, libraries, and configuration files. Containers can communicate with each other through well-defined channels.

If you don’t want to spend your days setting up and configuring your work environment then you might think about trying Docker out.

In what follows, I assume you have already installed Docker CLI. If you don’t, please visit this link and install it 🐳.

Without further ado, let’s jump on the code!

Installing Vapor & creating a new project

First of all, let’s install vapor toolbox:

Type the following to check everything works as expected.

You should see a list of available commands.

We can now use vapor CLI commands to create a new project. Notice that I left a change directory command commented as you might want to create the project in a new directory if you still are in the toolbox directory.

We won’t be covering the app organization in this article. As a line guide, think of the main.swift as the entry-point of your app where you bootstrap the server and do that stuff your server needs to start working. The sources folder contains your application whereas Tests, remarkably, contains the tests. Package.swift is the manifest file for your project.

Instead, we are quickly going to look into the routes file. So, let’s just navigate to the swift file containing the routes and replace the string “world” with an emoji.

Open the newly created project with your favorite editor. On Visual Studio Code, it should look like the following:

Vapor starter codebase

As you can see the syntax is sweet and clean. First, you import Vapor and you define a throwable function called route. Then, inside that function, you define two get functions. In our example, we define two GET endpoints: / and /hello.

Next, let change what Go inside the function app.get(“hello”) and replace the return statement like so:

Build and run the server with Docker.

Vapor ‘new’ command automatically generates a Dockerfile inside the project directory. It should look like the following.

Since you don’t need the Swift compiler to run your server, the Dockerfile separates build and run images. Consequently, the final output of the Dockerfile will be extremely lightweight. This makes the Swift server quite handy in a microservices infrastructure.

We can now build and serve the app!

If you navigate to your localhost:8080/hello, you should see the following:

Congratulations! You ran your first Swift hello world server!

Final words

Swift’s community will thrive as more developers join it. We are still at an early adoption phase but thanks to huge projects such as Tensorflow Swift and Fastai, Swift adoption might get a lot of traction. I hope this article inspired some to give Swift a shot. In the future, I am gonna add more content and tutorials regarding Swift and its applications.

I would love to hear your thoughts about it. So please feel free to share anything with me.

Ciao,
Michele

Here is the link to the repository

--

--