Swift™ + Cloud Run.
The Swift logo is a trademark of Apple Inc. Use of the Swift Logo is used according to this technical publication related to teaching the Swift programming language.

Swift (🔗) is an innovative, open source programming language developed by Apple to make software everywhere safer, faster, and more fun to create.

Vapor (vapor.codes) is a non-blocking, event-driven architecture built on top of Apple’s SwiftNIO, written in Swift with a focus on type-safety.

Together, you can build powerful web services that can be hosted on top of Cloud Run. This blogpost will give you a quick start for doing just that.

Prerequisites

To use Swift, you need one tool, Xcode.

  • Install Xcode 11.4+ (for free) via the App Store
  • Open Xcode and install any updates.
  • Ensure Swift is available in your terminal: swift --version

Setup Vapor

For our application, we’ll use the open source web framework, Vapor.

  1. Install vapor via Homebrew:
brew install vapor/tap/vapor

2. Open a new terminal window and create a new Vapor project: vapor

vapor new Hello

3. Say n to usingFluent when prompted.

Your terminal should look like this:

vapor CLI

Setup your Xcode project using the Vapor Toolbox:

cd Hello && vapor xcode
Note: Xcode is a great way to develop Vapor apps, but use any editor you like.

To build and run your Vapor app, ensure you have the Hello scheme we created and My Mac device is selected:

Xcode should show your “Hello” program in the toolbar with “My Mac” scheme.

Once that’s selected, just click the ▶ button or press ⌘R. You’ll notice logs stating: Server starting on http://127.0.0.1:8080.

Go to http://localhost:8080/ to test your web server. You should see:

It works!

Inspect the Code

Within Xcode, you should be able to dive into the source code and see logs:

A full screenshot of an Xcode workspace window.

I won’t go through the full application, but the main program has a default router for / GET requests and a router for /hello GET requests:

Debug with Breakpoints

Debug your app by adding breakpoints and inspect using the Debug area:

Test Locally

A sample unit test is under Tests. To run your unit tests, press Command + U.

The notification when tests succeed in Xcode.

Deploy to Cloud Run

Easily deploy your web application to Cloud Run by first building then deploying your Docker container image (using the generated Dockerfile):

In my case, it took 10m23s to build the container.

Here’s the above Swift/Vapor app deployed on Cloud Run:

https://vapor-q7vieseilq-uc.a.run.app

You’re running an autoscaling container-based web server written in Swift! 🎉

Thanks for Reading!

If you liked this blogpost, you might also like these other learning resources: