How can I use swift in Terminal?
I read What's new in Xcode 6. The article introduces some new feature about Xcode 6, and it says:
Command Line
Xcode’s debugger includes an interactive version of the Swift language, known as the REPL (Read-Eval-Print-Loop). Use Swift syntax to evaluate and interact with your running app or write new code in a script-like environment. The REPL is available from within LLDB in Xcode’s console, or from Terminal.
I want to know how to get the REPL?
Solution 1:
sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer
then you can do one of these:
xcrun swift
lldb --repl
As of Xcode 6.1 - typing swift
in the terminal launches the REPL as well.
Solution 2:
Alternatively, if you don't want to mess up your current dev environment, you can just run:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift
Solution 3:
Step 1: Open Terminal
Step 2: Type "swift"
Step 3: There's no step 3
Example:
GoldCoast:~ macmark$ swift
Welcome to Swift! Type :help for assistance.
1> println("Hello, world")
Hello, world
2> var myVariable = 42
myVariable: Int = 42
3> myVariable = 50
4> let myConstant = 42
myConstant: Int = 42
5> println(myVariable)
50
6> let label = "The width is "
label: String = "The width is "
7> let width = 94
width: Int = 94
8> let widthLabel = label + String(width)
widthLabel: String = "The width is 94"
9> :exit
GoldCoast:~ macmark$
Solution 4:
In Xcode 6.1.1 with Command Line Tools installed you can execute scripts by referencing directly to /usr/bin/swift
the following way:
#!/usr/bin/swift
let variable: String = "string"
print("Test \(variable)")