Setup Swift REPL and Access from the Command Line

Swift has a very nice Read-Eval-Print-Loop (REPL) for developers to take advantage of and be able to get instant feedback on Swift code.  This is great for trying things out without having to use Xcode 6 and a full project.

If you are unsure of what this REPL is, from the Swift web site:

Read-Eval-Print-Loop (REPL). The debugging console in Xcode includes an interactive version of the Swift language built right in. Use Swift syntax to evaluate and interact with your running app, or write new code to see how it works in a script-like environment. Available from within the Xcode console, or in Terminal.

The problem is, it’s not available by default since it’s not in your path.  If you have Xcode 5 installed you probably don’t want to have to deal with switching back and forth between Xcode paths.

The solution is pretty simple actually.  I wanted to be able to get to Swift from the terminal with a short command, in this case, swift will be the command.  In order to setup it up I located the swift binary, yours may be different depending upon where you have the Xcode 6 beta installed.  Mine was here:

/Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift

If you just run that line in terminal it works fine but I want to be able to access this easily.  The answer is an alias added to the .bash_profile.  Add this line to the .bash_profile:

alias swift="/Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift"

Restart the terminal app, type swift and you should see something like this:

Swift term

UPDATE (06/17/2014): Apple released Xcode 6 Beta 2 today and the path changes to where the Swift binary lives, use Xcode6-Beta2.app instead of Xcode6-Beta above.

  • Pingback: Using Swift As General Purpose Scripting Language - StrathWeb()

  • surryhill

    Instead of the absolute path I recommend using: xcrun swift

  • http://www.accidentaltechnologist.com Rob Bazinet

    Yeah, you can do that but then you need to set which Xcode install you are using first. If my main is Xcode 5.x and I want Swift from terminal then I have to switch to Xcode 6. My way, I don’t have to and can keep running Xcode 5 without issue.

  • surryhill

    Good point. With xcode-select -switch I also switch my brain from normal to experimental mode ; )

  • http://www.manuelmeurer.com/ Manuel Meurer

    Why not just symlink the file to /usr/local/bin/swift?

  • http://www.accidentaltechnologist.com Rob Bazinet

    Well…maybe because I didn’t think of it? LOL, very good point. It never crossed my mind but probably the most simple. Thanks for sharing.

  • http://www.manuelmeurer.com/ Manuel Meurer

    Hehe, no problem. I find symlinking easier than adding stuff to the PATH, because it makes finding the executable easier (look in /usr/local/bin, /usr/bin and /bin)

  • Pingback: Using Swift for Shell Scripting [iOS developer:tips];()