Command-Line Interfaces in Swift

Posted on Sun 03 June 2018 in Swift

This is a new blog about my journey learning Swift by writing command-line tools (in fact, probably just one or two command line tools). I'm writing it mostly as reference for myself, but also in the hope that it might help someone else.

It is Sunday 3rd June 2018 and I have written command-line tools in many languages for over 30 years. I have played with Objective-C, writing a few unreleased iOS apps, and a few months ago I did a little iOS development in Swift, but not much.

This time, I want to start without all the GUI stuff and just concentrate on the fundamentals of Swift the language, rather than iOS and Mac OS GUI development. I might come to that later.

At the time of writing (one day before WWDC 2018), Swift is at 4.1. My plan is to translate a couple of command-line apps I already have in Python (my main daily language), and in this blog, I plan to show little experiments that I need in order to know how to perform the translation. In doing so, we'll probably develop a small generic command-line interface, but no promises.

I won't be using Xcode (the IDE), per-se, but rather editing files, as usual, in Emacs and just dumping the code into the blog. I'll just be compiling with swiftc.

I make no promises that I'll come back and update the code as necessary if and when changes to the language and or the libraries necessitate it, but I will clearly mark what version of Swift and Xcode are used used on each post, and try hard to update that if I update the code.

The posts certainly aren't intended as an introduction to programming, but they might serve as a useful conversion series for anyone coming from another (probably imperative) language.

Below is a non-exhaustive list of basic tasks I'll probably try to cover over the coming weeks and months. Notice that most of these are capabilities, rather than language features, though we'll obviously eun across language features along the way.

  • Compiling Swift
  • "Hello, World!" (printing)
  • Getting arguments from the command line
  • Reading from lines the keyboard and building a REPL
  • Reading and writing files (text, binary)
  • HTTP GET, PUT, POST, DELETE (and probably not PATCH)
  • Writing tests
  • Manipulating strings (walking strings, concatenation, stripping, substrings etc.)
  • Regular expression matching
  • Text encoding (and representation)
  • Exception handling
  • Option parsing (a special case of handling command-line arguments)

Code

The code featured in the blog will be available on Github at github.com/njr0/cli-swift-examples

Feedback

I'll undoubtedly get stuff wrong, and (maybe) this blog will occasionally be read by more experienced Swift developers (hi @clatter_llvm). Do ping me on Micro.Blog (@njr) or Twitter (@njr0) when I get stuff wrong, am unidomatic or there's a better way. Or file an issue or pull request on Github.