Creating human-readable Swift tool with Xcode
One of the (few) nice things about a shell script is that if you share it with someone, they can look at the source code and see how it works or modify it for their own purposes.
It’s not as quick and dirty as a bash script, for example, but it has some big advantages:
- It’s Swift and it’s a great way to learn it and reduce the number of languages you need to know
- You can use Xcode to create the tool and have the full power of Xcode debugging
- Writing tools in bash can be very frustrating due to the unusual syntax and lack of some modern language features.
There’s one downside though. The output from Xcode is a compiled binary, so people have to check out your source code from a repository to see how it works. So, here’s what you can do after you’ve created your project. A caveat is that you must keep all your code in main.swift for this to work, which is probably likely anyways for a tool.
At the top of main.swift, add this line:
#!/usr/bin/swift
This is ignored by the compiler.
- Click on the project in the sidebar
- Click on Build Phases
- Click on the (+) button in the upper left of the content area and choose New Run Script Phase
Below the shell field, add a script that looks like the following:
Here it is so you can copy and paste.
#!/bin/bash
PATH=”$PROJECT_DIR/$PROJECT_NAME/main.swift”
/bin/cp $PATH ~/bin/$PROJECT_NAME.swift
/bin/chmod +x ~/bin/$PROJECT_NAME.swift
- In my case, I chose to have the script written to my ~/bin folder, so edit that to what you like
- When building the project, the run script phase will take your main.swift file and rename it to <project name>.swift, make it executable, and move it to the location of your choosing
- Run the script just by typing the path, just like with a shell script
Now your script works just like the binary except you can share it with people and they can see the source code, editing it as they wish. You can then create a template project with all this set up already and then duplicate it whenever you want to create a new tool.
Extra credit
This works with any shell executable file, but if you change the extension to “.command” it will be double-clickable in the Finder.