Solarian Programmer

My programming ramblings

Getting started with Swift 3 on Linux

Posted on November 8, 2016 by Paul

In this article, I will show you how to install and use Swift 3 on Linux. Swift is officially tested and supported on Ubuntu Linux. I will assume that you have Ubuntu 16.04 installed on your server or on your local computer.

First, make sure that you have an up to date system:

1 sudo apt update
2 sudo apt upgrade

Next, install Clang which is required if you want to be able to use the Swift compiler:

1 sudo apt install clang libicu-dev

You can download the official Swift binary for Ubuntu 16.04 from swift.org. Chose the latest stable release (currently this is version 3.0.1). If you see a new version of Swift, update the URL from the next instructions accordingly:

1 wget https://swift.org/builds/swift-3.0.1-release/ubuntu1604/swift-3.0.1-RELEASE/swift-3.0.1-RELEASE-ubuntu16.04.tar.gz
2 tar xzf swift-3.0.1-RELEASE-ubuntu16.04.tar.gz
3 sudo mv swift-3.0.1-RELEASE-ubuntu16.04 /usr/local
4 rm swift-3.0.1-RELEASE-ubuntu16.04.tar.gz

At this point, you have Swift installed. Next step is to add it to your system PATH:

1 export PATH=/usr/local/swift-3.0.1-RELEASE-ubuntu16.04/usr/bin:$PATH

If you want to permanently add Swift to your PATH, use:

1 echo 'export PATH=/usr/local/swift-3.0.1-RELEASE-ubuntu16.04/usr/bin:$PATH' >> .profile
2 source .profile

Let’s check the version of Swift installed. This is what I see on my machine:

1 $ swift --version
2 Swift version 3.0.1 (swift-3.0.1-RELEASE)
3 Target: x86_64-unknown-linux-gnu
4 $

You can start a Swift REPL with the swift command, after which you can start writing Swift. When you want to to close the REPL, use :q. Here is a simple example of a Swift REPL session:

1 $ swift
2 Welcome to Swift version 3.0.1 (swift-3.0.1-RELEASE). Type :help for assistance.
3   1> let site = "solarianprogrammer.com"
4 site: String = "solarianprogrammer.com"
5   2> print("Hello from \(site)")
6 Hello from solarianprogrammer.com
7   3> :q
8 $

If you want to compile a Swift code, you will use the swiftc command. Open a new text file and copy the next piece of code:

1 let site = "solarianprogrammer.com"
2 print("Hello from \(site)")

save the file as “Hello.swift”. You can compile and run the code with:

1 swiftc Hello.swift
2 ./Hello

If you are interested to learn more about the latest Swift syntax, I would recommend reading Swift Programming: The Big Nerd Ranch Guide (2nd Edition) by M Mathias, J Gallagher:


Show Comments