If you want to start learning swift without firing up an IDE, this post is for you. This post was written because the instructions in the references are slightly out of date.

Software Versions

$ date
January 18, 2016 at 09:01:44 AM JST
$ uname -a
Darwin siderite.centurylink.net 15.2.0 Darwin Kernel Version 15.2.0: Fri Nov 13 19:56:56 PST 2015; root:xnu-3248.20.55~2/RELEASE_X86_64 x86_64
$ swift --version # swiftc is the same
Apple Swift version 2.1.1 (swiftlang-700.1.101.15 clang-700.1.81)
Target: x86_64-apple-darwin15.2.0

Instructions

Create a simple swift script with a shebang at the top. Add the following to arg_echo.swift

#!/usr/bin/env swift
print("Command line arguments:")
for arg in Process.arguments {
  print(arg)
}

Make the script executable.

chmod +x arg_echo.swift

The script can be run from the command line.

./arg_echo.swift a b c

Alternatively, run the script with the swift command. In this case, the shebang is unneccessary.

swift arg_echo.swift a b c

Use swiftc to compile an executable. The shebang will be ignored when compiling, so the above source code will work unchanged.

swiftc arg_echo.swift -o arg_echo

The executable can be run from the command line.

./arg_echo a b c

References: