Swift REPL
Back in the early 80s I learned the power of LISP’s REPL (Read-Eval-Print-Loop). (As a music major, mind you). Clojure gave us a REPL for the Java JVM. Kids today use Python’s REPL. Swift playgrounds are peachy, but are a bit buggy right now.
Set up
First, you need to say you want to use XCode 6 beta’s Developer Toolchain. Here is the incantation.
1 |
sudo xcode-select -s /Applications/Xcode6-Beta.app/Contents/Developer/ |
(or Xcode6-Beta2.app if you have that installed now)
And to go back to XCode 5:
1 |
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer/ |
You might want to define aliases for those in your shell’s .rc file. You could also just set your shell’s DEVELOPER_DIR environment variable to point to it too.
1 |
DEVELOPER_DIR=/Applications/Xcode6-Beta.app/Contents/Developer/ xcrun swift |
Using the REPL
Find out which SDKs are available:
1 |
xcodebuild -showsdks |
Then run with one of the listed SDKs.
1 |
xcrun --sdk iphoneos8.0 swift |
or
1 |
xcrun --sdk macosx10.10 swift |
Read the man page xcrun(1) for more info.
1 |
man 1 xcrun |
Once inside the REPL, you can type :help, or :quit to exit. Control-D works for me too to exit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
xcrun --sdk iphoneos8.0 swift Welcome to Swift! Type :help for assistance. 1> var a = 2 a: Int = 2 2> a + a $R1: Int = 4 3> func foo() -> String {return "hello"} 4> foo() $R2: String = "hello" 5> var re = foo() re: String = "hello" 6> re $R3: String = "hello" 7> println(re) hello :quit |
Use Swift in a shell script? Chris Lattner tweeted this.
Here’s a simple script.
1 2 3 |
#!/usr/bin/env xcrun swift -i println("Hello World!") |