There's more...

It's great to try out Swift code at the command line using the REPL, but what we really require is the ability to compile our code into an executable binary that we can run on demand. Let's take our "Hello world!" example and compile it into a binary:

  1. Open your favourite text editor and save the following into a file called HelloWorld.swift:
print("Hello world!")
  1. From the command line, in the folder that contains our Swift file, we can compile our binary using swiftc:
swiftc HelloWorld.swift -o HelloWorld
  1. You specify the file or files to compile and use the -o flag to provide a name for the output binary.
  2. Now, you can execute the binary:
> ./HelloWorld
> Hello world!

Compiling one file is great, but to perform any useful work, we are likely to have multiple Swift files that define things like models, controllers, and other logic, so how can we compile them into a single, executable binary?

When you have multiple files, which one is the entry point to your application? When compiling a Swift binary with multiple files, one of them should be called main.swift, and the code in this file will be executed when the binary is executed; this serves as the entry point to your application.

Let's make two Swift files, first one named Model.swift:

// Model.swift

class Person {
let name: String
init(name: String) {
self.name = name
}
}

Next, we'll create the main.swift file:

// main.swift

let keith = Person(name: "Keith")
print("Hello \(keith.name))

Now, let's compile these two files into a binary called Greeter:

swiftc Model.swift main.swift -o Greeter

This can then be executed:

> ./Greeter
> Hello Keith!

We have now written and compiled a multifile binary in Swift on Ubuntu.