Swift tries to be a jack of all trades, but I think as a scripting language (as in this example) it falls short. Having to start a run loop, write asynchronous callbacks (completion handlers), and implement custom JSON decoders just to make a web request is introducing a ton of complexity that might make sense in an event-driven interactive GUI application, but not so much in a quick shell script.
Swift tools might be a good choice for use cases where you need to integrate with an existing Swift project, or if you need lower level APIs.
In this example, a Bash script would have been almost done by the time you worked out the `curl | jq` command. But in other similar cases I would suggest Python Requests, which will take perhaps 10% as much code and avoid issues of Linux compatibility and mistakes like forgetting to call `resume()` on your download task or `exit()` in some branch (there are five calls just to keep the program from looping forever).
That said, I think this blog post is very informative and well-made for a beginner interested in talking to a web-based JSON API from Swift.
Swift as a (shell) scripting language has been terrible for me. To get us to Swift shell scripting, I think what's needed is the "syntax" for calling out to other executables directly instead of wrapping it in a task. Of course, plumbing follows immediately and I don't know if we can keep the shell plumbing syntax in a Swift environment.
That should be doable with a library, right? Is there any need for language syntax for this?
- The official libraries that ship with Swift
- If you create a full-blown Swift package manager project and compile an executable. But this doesn't sound like a script anymore
- If you use John Sundell's Marathon [https://github.com/JohnSundell/Marathon] however it adds additional complexity around the writing of scripts
I.e. none of the solutions are as simple as writing a bash script
Edit: Just saw that Max Howell (creator of Homebrew) released this today https://github.com/mxcl/swift-sh This absolutely solves the issues. Fantastic.