Command-Line Arguments (argv and argc) in Swift

Posted on Sun 03 June 2018 in Swift

There are two main styles of command-line tool. One of them takes its inputs on the command line, does something, and exits. The other starts, reads input from the keyboard and responds until some exit condition is met, and then exits. This second style of program is often called a REPL—a Read, Evaluate, Print Loop.

We're going to start with the first of these, and the fundamental requirement for writing such a tool is getting access to those command-line argument (argv, and perhaps argc, in C-terms).

Here's a trivial Swift program that just shows what the arguments were, and counts them, based in information in this post

// argv.swift
//
// Collect, echo and count command-line arguments
// [Swift 4.1; Xcode 9.3.1; 2018-06-03]
//
// https://stackoverflow.com/questions/24029633/how-do-you-access-command-line-arguments-in-swift
//


print(CommandLine.arguments)
print(CommandLine.arguments.count)

Here's what happens in a few cases after compilation:

$ ./argv
["./argv"]
1
$ ./argv one
["./argv", "one"]
2
$ ./argv one 2
["./argv", "one", "2"]
3
$ ./argv one && echo done
["./argv", "one"]
2
done

About the points to note are:

  • CommandLine.arguments either is or acts like an array of Strings. (the note on ARGC in this article suggests it might be array-like, but it doesn't make any different at least for simple uses.)
  • We can use the .count property to access the number of arguments
  • As with argv in C, the command itself is the first element in the array
  • the last example illustrates that, as expected, the shell only passes the intended arguments to the command