ArgParser

A ridiculously simple argument-parsing library for Swift.

Version 3.0.0

Command Line Interface



Options

An option can have an unlimited number of long-form aliases and single-character shortcuts: --option, -o.

Option values can be separated by either a space, --option 123, or an equals symbol, --option=123. Either syntax can be used with shortcuts: -o 123, -o=123.

Multiple shortcuts can be condensed into a single block, e.g. -abc foo bar. Trailing arguments are consumed in sequence as required by the options.

Multivalued Options

Options can be treated as singular or multivalued as circumstances require. Each option maintains an internal list to which newly parsed values are appended; the (singular) value of the option is the final value in the list.

For example, in the command below:

$ my_app --foo abc --foo def

the value of the option foo is "def" but the array ["abc", "def"] is also available for use if required.

Flags

Flags are valueless options — they're either present or absent, but take no arguments. Like options, flags can have an unlimited number of long-form aliases and single-character shortcuts: --flag, -f.

Positional Arguments

Options and flags can be preceded by, followed by, or interspaced with positional arguments which are assembled by the parser into an array of strings.

The parser supports the standard -- switch for turning off option-parsing. All arguments following a -- will be treated as positional arguments, even if they begin with a single or double dash.

Quoted Values

Note that you can use quotes to surround argument and option values containing spaces, e.g.

$ my_app "arg 1" "arg 2"
$ my_app --option "value with spaces"
$ my_app --option="value with spaces"
$ my_app -o="value with spaces"

This isn't a feature of the library — the quotes are processed by the shell and the library only sees the resulting string values, including spaces.

Commands

This library supports git-style command interfaces with arbitrarily-nested commands. Commands have builtin support for an automatic --help flag and an automatic help <cmd> command, i.e. the commands

$ my_app <cmd> --help

and

$ my_app help <cmd>

are functionally identical and will both print the help text registered with the command.

Non-Unicode Arguments

To keep its API simple this library uses Swift's native String type which can only represent valid unicode strings.

You should be aware that on Unix systems command line arguments can contain arbitrary byte values, not just valid unicode. Swift doesn't raise an error if this happens — instead it silently replaces unrepresentable byte values with the unicode replacement character (U+FFFD).

Negative Numbers

Some argument-parsing libraries struggle with negative numbers — for example, they will try to parse -3 as a flag or option named 3. This library always treats arguments beginning with a dash and a digit as positional arguments or option values, never as flag or option names.