-
Notifications
You must be signed in to change notification settings - Fork 5
interpreting
If you want to create interpreted Swift scripts (as opposed to compiling into as a seperate binary and running from said binary) similar to how other scripting languages work (such as bash or Python), you will need two things:
- The Shebang
- The
chmod
Command
You will need to add a single line of code to the very top of your file:
#!/usr/bin/env xcrun swift
From Wikipedia:
Under Unix-like operating systems, when a script with a shebang is run as a program, the program loader parses the rest of the script's initial line as an interpreter directive; the specified interpreter program is run instead, passing to it as an argument the path that was initially used when attempting to run the script.
In other words, when we run our program, /usr/bin/env xcrun swift
invokes the Swift environment and passes it the path to our program as an argument. In a traditional scripting language, this environment would be an interpreter. In the case of Swift, it compiles our script behind the scenes and runs from a binary that we never see. This is the key to making our script executable with the chmod
command.
For all intents and purposes, we are using Swift as an interpreted language.
Note: This is also how executing Swift programs inline from the terminal works:
$ swift myprogram.swift
(Which is why we don't need shebangs for scripts executed inline.)
After adding the shebang to the top of our script file, we head over to the terminal and change its access level to be executable:
$ chmod +x myprogram.swift
Now we can run our script simply by calling it directly:
$ ./myprogram.swift
# program does something...
Take the following script, HelloWorld.swift:
#!/usr/bin/env xcrun swift
// HelloWorld.swift
println("Hello, World!")
In the terminal:
$ cd /path/to/script/
$ chmod +x HelloWorld.swift
$ ./HelloWorld.swift
Hello, World!
If you would like to import third party frameworks into your script, use the following Shebang:
#!/usr/bin/env xcrun swift -F /Library/Frameworks
We have to do this because the Swift compiler does not automatically search the /Library/Frameworks/
directory. You could also specify other framework directories to search if you use a different location to store your frameworks.
With the shebang & chmod
, we can build simple Swift scripts that don't require large, complex Xcode projects to manage creation, compilation, etc. Need to make a change? After a script is made executable, it's as simple as editing the file and pressing save. No recompiling necessary. Need to import a custom framework? Easy.