It recently came to my attention that trying to import packages into Google Colab for Swift is extraordinarily difficult.
When looking around on the internet on ways to do this, 2 links came up. One link points to a GitHub gist that shows you how to import packages in a long, tedious way, and the other points to a two-year-old forum that is 20+ responses long. Yet, neither gives a general, easy to do command that rivals Colab’s Python pip install
.

In order to remedy this, I just spent the last 3 hours figuring out how to import packages into colab with a one liner.
Turns out all you need to do is type in:
%install '.package(url: "{GITHUB URL}", from: "{GITHUB REPO VERSION}")' {PACKAGE NAME}
Where you would replace the {INSERTS}
with the proper information.
—
An example would be:
%install '.package(url: "https://github.com/dankogai/swift-complex", from: "5.0.0")' Complex
This installs the Complex
package for Swift (because the built-in one is utter 💩). The output looks something along the lines of:
Installing packages: .package(url: "https://github.com/dankogai/swift-complex", from: "5.0.0")
Complex With SwiftPM flags: []
Working in: /tmp/tmpmc6wisrl/swift-install
Fetching https://github.com/dankogai/swift-complex
Cloning https://github.com/dankogai/swift-complex
Resolving https://github.com/dankogai/swift-complex at 5.0.0 [1/7]
Compiling Complex GaussianInt.swift [2/7]
Compiling Complex Complex.swift [3/7]
Compiling Complex FloatingPointMath.swift [4/8]
Merging module Complex [5/8]
Wrapping AST for Complex for debugging [6/8]
Linking libComplex.so [7/9]
Compiling jupyterInstalledPackages jupyterInstalledPackages.swift [8/10]
Merging module jupyterInstalledPackages [9/10]
Wrapping AST for jupyterInstalledPackages for debugging [10/10]
Linking libjupyterInstalledPackages.so [10/10]
Linking libjupyterInstalledPackages.so
* Build Completed!
Initializing Swift...
Installation complete!
—
As you can see, this one command both installs and automatically builds the package – essentially the equivalent of pip install
!
Now go out and write some Swifty code!
—
Quick note: When you start your Colab notebook, the first line you run must be the package install command. I have no idea why, but Colab forces you to do this first