Using Swift as an interpreter
Like some other script languages, you can use Swift with its interpreter on the command line. Sometimes it's very useful, mainly when you want to test code but you don't want to create a new playground.
Getting ready
Open a terminal window as it was shown in the previous recipe.
How to do it...
Follow these steps for using Swift as a command line interpreter:
- The first step is to find where the Swift command is; even if you have used the
xcode-select
command, it is possible that the Swift command is not accessible from yourPATH
variable. So, you can localize your Swift command usingfind /Applications/Xcode.app -name swift -a -type f.
In my case, I got/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift
. However, current versions of Xcode have the Swift command at/usr/bin
. If it is necessary, add this directory to your PATH variable with the commandexport PATH="$PATH:/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/"
. At this moment, we can enter into the Swift interpreter just typingswift
. - If you want to use Swift from the command line, sometimes, it's a good idea to have this
PATH
variable set permanently. To make this, we need to add the previous command into our.profile
file, such asecho 'export PATH="$PATH:/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/" ' >> $HOME/.profile && chmod +x $HOME/.profile
. From now on, if you restart your computer, it won't be necessary to look for the Swift path and set thePATH
environment variable again. - Now, let's enter into our Swift command line and type the following code:
var dividend = [3,2,1,0] var divisor = 6
- You will see a message showing the content of these variables after typing each of them. Now, type the following loop code:
for i in dividend { println("\(divisor) / \(i) = \(divisor / i)") }
- Now, you can see that we will receive the following result:
6 / 3 = 2 6 / 2 = 3 6 / 1 = 6 Execution interrupted. Enter Swift code to recover and continue. Enter LLDB commands to investigate (type :help for assistance.)
- As you can see, the last option failed because we can't divide by 0 and that's a fast way we can test some code, using the command line. Most of the time, we will test using a playground, but sometimes using the command line is much faster.
How it works...
Calling the Swift command gives you the possibility to test your code or even use Swift as a scripting language. The highlight here is that you need to know where your Swift command is; the command line helps you to find it.
There's more...
Most of Swift's options and swiftc
options are common; it means that if there is something that you would like to test before compiling, you can do it.