Let’s setup a swift development environment on Ubuntu 18.04. “Why?”, you might ask, as swift was written by Apple for Mac and iOS development and I do happen to have a Apple Mac with everything installed there, my answer is “why not”, let’s give it a try.
- Go to https://swift.org/download/#releases and locate the version of Swift you want to download, I picked Swift 5.3.2, Ubuntu 18.04. Download this to your machine.
- From ~./Downloads run
tar -xvzf swift-5.3.2-RELEASE-ubuntu18.04.tar.gz
Obviously replace the .tar.gz with whatever version you download.
- Now would probably be a good time to move the resultant decompressed folder to where you want it to be kept, mine’s in a ~/Home/swift directory.
- Open .bashrc and add the following line (or just export the path if you want it temporary without adding to .bashrc)
export PATH=$PATH:$HOME/swift/swift-5.3.2-RELEASE-ubuntu18.04/usr/bin
Don’t forget to save the .bashrc file if you’ve gone that route and ensure the path to swift usr/bin matches where you moved your files to
- I’m going to use VSCode, as my editor, and there’s several Swift extensions, I installed Swift Language 0.2.0. This has the largest number of downloads, I’ve no idea how good this is compared to others, but that’s the one I’ve installed for now.
- If all went well, open a terminal window in VSCode or just use the a bash terminal and type
swift --version
If all went well you’ll see the Swift version and Target listed
Getting Started
Now we have swift installed (hopefully), let’s look at the sort of “Getting Started” type of things you’ll want to try.
Let’s use the swift command to create a simple executable application. So run the following for your terminal
swift package init --type executable
This will use swift’s package manager to create a new executable application with good old “Hello World”.
To build this, simple execute the following command
swift build
and to run this we simply execute the command
swift run
When making changes to your code you can actually just save the file(s) and use the run command which will build and run the application.
The command which generated this source created a Package.swift file which is where we add dependencies etc. Source code is stored in the Sources folder, and here the file is named main.swift which simply contains
print("Hello World!")
In the Tests folder we have the tests for the application. We’re not going to go into those now except to say, you can run the following command to run the tests
swift test