Command Line Flags in Swift

Here’s the translation of the Go code to Swift, along with explanations in Markdown format suitable for Hugo:

Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.

Swift doesn’t have a built-in flag parsing library like Go’s flag package, but we can use the ArgumentParser library, which is part of Swift’s package ecosystem. First, we need to add it to our project’s dependencies.

import ArgumentParser
import Foundation

struct CommandLineFlags: ParsableCommand {
    @Option(name: .long, help: "A string")
    var word: String = "foo"

    @Option(name: .long, help: "An int")
    var numb: Int = 42

    @Flag(name: .long, help: "A bool")
    var fork: Bool = false

    @Option(name: .long, help: "A string var")
    var svar: String = "bar"

    mutating func run() throws {
        print("word:", word)
        print("numb:", numb)
        print("fork:", fork)
        print("svar:", svar)
        print("tail:", CommandLine.arguments.dropFirst())
    }
}

CommandLineFlags.main()

In this Swift version, we define a CommandLineFlags struct that conforms to the ParsableCommand protocol. This allows us to declare our command-line options using property wrappers:

  • @Option is used for options that take a value (like --word=value)
  • @Flag is used for boolean flags (like --fork)

The run() method is where we put the logic that runs when the command is invoked. Here, we’re just printing out the values of our options.

To experiment with the command-line flags program, you’ll need to compile it first:

$ swift build

Try out the built program by first giving it values for all flags:

$ .build/debug/CommandLineFlags --word=opt --numb=7 --fork --svar=flag
word: opt
numb: 7
fork: true
svar: flag

Note that if you omit flags, they automatically take their default values:

$ .build/debug/CommandLineFlags --word=opt
word: opt
numb: 42
fork: false
svar: bar

Trailing positional arguments can be provided after any flags:

$ .build/debug/CommandLineFlags --word=opt a1 a2 a3
word: opt
numb: 42
fork: false
svar: bar
tail: ["a1", "a2", "a3"]

The ArgumentParser library automatically generates help text for the command-line program. Use --help to see it:

$ .build/debug/CommandLineFlags --help
USAGE: command-line-flags [--word <word>] [--numb <numb>] [--fork] [--svar <svar>]

OPTIONS:
  --word <word>           A string (default: foo)
  --numb <numb>           An int (default: 42)
  --fork                  A bool
  --svar <svar>           A string var (default: bar)
  -h, --help              Show help information.

If you provide a flag that wasn’t specified, the program will print an error message and show the help text.

This Swift version provides similar functionality to the original Go program, using Swift’s ArgumentParser library to handle command-line argument parsing.