Scripting and Compiling Swift on the Command Line

April 4, 2017

Apple’s Swift programming language is most widely used for iOS and macOS development in Xcode, however, it can also be used in a manner more like a traditional Unix shell script or even compiled into an executable using the command line. Below, I give some examples of these alternative uses.

For scripting, like other shell scripts, the first line of your script’s .swift file should be a “shebang”, which points to the swift executable. Following that, you can write Swift code as usual:


func fibonacci(_ n: Int) -> Int {
    if n <= 2 {
        return 1
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2)


You can make the script executable and run it as you would any other shell script:

% chmod +x fibonacci.swift
% ./fibonacci.swift

Printing the 10th integer in the Fibonacci sequence is hard coded above, but what if you want to print other values? We can modify the script to take a single command line argument, the index of the Fibonacci number you want to print. Replace the last line above with the following:

let arg = CommandLine.arguments[1]  // Store first argument.
if let n = Int(arg) {               // If it converts to Int,
    print(fibonacci(n))             // print fibonacci(n).
} else {                            // Otherwise,
    print("Usage: fibonacci <n>")   // print usage and exit.

Then invoke the script as follows:

% ./fibonacci.swift 36
% ./fibonacci.swift junk
Usage: fibonacci <n>

As with modern scripting languages such as Python and Ruby, you can also run Swift interactively (with Xcode 6.1 and later). The interactive command-line interface is called the Swift Read Eval Print Loop (REPL):

% swift
Welcome to Apple Swift version 3.1 (swiftlang-802.0.48 clang-802.0.48). Type :help for assistance.
  1> 1 + 2
$R0: Int = 3
  2> print("hello, world")
hello, world

Finally, you can also compile Swift code and run it as a binary:

% swiftc -o fibonacci fibonacci.swift
% ./fibonacci 7

As with C and other languages, you can compile multiple Swift files:

% swiftc first.swift second.swift third.swift -o program

Note: These instructions are valid on macOS Sierra with Xcode 8.3 and Swift 3.1, but as the Swift language evolves they may change.