With the REPL (Read-Eval-Print Loop) environment of Swift, we can do some simple interactive programming with Swift. Every input statement would be executed immediately and provide an output. It is a shared feature in all interpreted languages (while Swift is a compiled language itself). With the interactive environment, beginners can learn the language much quicker.

To launch the REPL, we would use the swift command line tool. First of all, we should confirm if we are using the latest command line tool by:

> xcode-select -p

in terminal. Xcode 6.1 or later is required to run the REPL. If you are using an older version of Xcode command line tool, a simple way to change it is choosing the correct one from "Command Line Tools" option in "Locations" tab of Xcode preference.

When prepared, type xcrun swift in terminal to start using.

It must be kept in mind that REPL is just behaving as an interpreted environment. The code is compiled to run every time you finish a statement under the hood. This limits us to do things too complicated in REPL.

Another way to run a snippet of Swift is passing a .swift file as input of the swift command. All code in the file would be compiled and run. Or we could even add the path of swift and add executable attribute to the file. By doing so, we can run the file directly, just like we do in other script language:

// hello.swift
#!/usr/bin/env xcrun swift
// Terminal
> chmod 755 hello.swift
> ./hello.swift

// Output

Developers who are familiar with interpreted languages will feel very comfortable with these cool features.

Another useful command is swiftc. It could compile one or more swift source to an executable binary. A file named main.swift will be the entry point of the binary:

// MyClass.swift
class MyClass {
    let name = "Tom"
    func hello() {
        print("Hello \(name)")

// main.swift
let object = MyClass()
> xcrun swiftc MyClass.swift main.swift

This would generate a main file. We can run it to see the result:

> ./main
// Output
// Hello Tom

By doing this, Swift can be used to write some command line programs now.

One more tip on this topic. Sometimes we need assembly code of the source. It will be useful when we need to know how the program running actually. By using swiftc we can achieve it easily:

swiftc -O hello.swift > hello.asm

Of course, there are a number of other powerful features of the command line tool. If you are interested in it, use xcrun swift --help and xcrun swiftc --help to learn more.

In newest version of Xcode, swift and swiftc command will be installed in /usr/bin/ when you choose to install the command line tools. It means we now could just use swift and swiftc to launch command line environment for Swift, instead of the xcrun way.