Peekaboo/docs/swift-argument-parser.md
Peter Steinberger 40acc9669b Fix deadlock in ImageCommand by replacing semaphore with RunLoop
- Remove DispatchSemaphore usage that violated Swift concurrency rules
- Implement RunLoop-based async-to-sync bridging in runAsyncCapture()
- Convert all capture methods to async/await patterns
- Replace Thread.sleep with Task.sleep in async contexts
- Keep ParsableCommand for compatibility, avoid AsyncParsableCommand issues
- Add comprehensive tests and documentation
- Improve error handling and browser helper filtering

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-06-08 09:41:50 +01:00

32 KiB
Raw Permalink Blame History

https://swiftpackageindex.com/apple/swift-argument-parser/1.5.1/documentation/argumentparser llms-full.txt

Swift Argument Parser

Skip Navigation

Framework

ArgumentParser

Straightforward, type-safe argument parsing for Swift.

Overview

By using ArgumentParser, you can create a command-line interface tool by declaring simple Swift types. Begin by declaring a type that defines the information that you need to collect from the command line. Decorate each stored property with one of ArgumentParsers property wrappers, declare conformance to ParsableCommand, and implement your commands logic in its run() method. For async renditions of run, declare AsyncParsableCommand conformance instead.

import ArgumentParser

@main
struct Repeat: ParsableCommand {
    @Argument(help: "The phrase to repeat.")
    var phrase: String

    @Option(help: "The number of times to repeat 'phrase'.")
    var count: Int? = nil

    mutating func run() throws {
        let repeatCount = count ?? 2
        for _ in 0..<repeatCount {
            print(phrase)
        }
    }
}

When a user executes your command, the ArgumentParser library parses the command-line arguments, instantiates your command type, and then either calls your run() method or exits with a useful message.

The output of the Repeat command, declared above.

Additional Resources

Topics

Essentials

Getting Started with ArgumentParser

Learn to set up and customize a simple command-line tool.

protocol ParsableCommand

A type that can be executed as part of a nested tree of commands.

protocol AsyncParsableCommand

A type that can be executed asynchronously, as part of a nested tree of commands.

Defining Commands and Subcommands

Break complex command-line tools into a tree of subcommands.

Customizing Help for Commands

Define your commands abstract, extended discussion, or usage string, and set the flags used to invoke the help display.

Arguments, Options, and Flags

Declaring Arguments, Options, and Flags

Use the @Argument, @Option and @Flag property wrappers to declare the command-line interface for your command.

struct Argument

A property wrapper that represents a positional command-line argument.

struct Option

A property wrapper that represents a command-line option.

struct Flag

A property wrapper that represents a command-line flag.

struct OptionGroup

A wrapper that transparently includes a parsable type.

protocol ParsableArguments

A type that can be parsed from a programs command-line arguments.

Property Customization

Customizing Help

Support your users (and yourself) by providing rich help for arguments, options, and flags.

struct ArgumentHelp

Help information for a command-line argument.

struct ArgumentVisibility

Visibility level of an arguments help.

struct NameSpecification

A specification for how to represent a property as a command-line argument label.

Custom Types

protocol ExpressibleByArgument

A type that can be expressed as a command-line argument.

protocol EnumerableFlag

A type that represents the different possible flags to be used by a @Flag property.

Validation and Errors

Providing Custom Validation

Provide helpful feedback to users when things go wrong.

struct ValidationError

An error type that is presented to the user as an error with parsing their command-line input.

struct CleanExit

An error type that represents a clean (i.e. non-error state) exit of the utility.

struct ExitCode

An error type that only includes an exit code.

Shell Completion Scripts

Generating and Installing Completion Scripts

Install shell completion scripts generated by your command-line tool.

Customizing Completions

Provide custom shell completions for your command-line tools arguments and options.

struct CompletionKind

The type of completion to use for an argument or option.

Advanced Topics

Manual Parsing and Testing

Provide your own array of command-line inputs or work directly with parsed command-line arguments.

Experimental Features

Learn about ArgumentParsers experimental features.

Structures

struct CommandGroup

A set of commands grouped together under a common name.

Extended Modules

Swift

Current page is ArgumentParser

| |

Customizing Completions

Skip Navigation

Article

Customizing Completions

Provide custom shell completions for your command-line tools arguments and options.

Overview

ArgumentParser provides default completions for any types that it can. For example, an @Option property that is a CaseIterable type will automatically have the correct values as completion suggestions.

When declaring an option or argument, you can customize the completions that are offered by specifying a CompletionKind. With this completion kind you can specify that the value should be a file, a directory, or one of a list of strings:

struct Example: ParsableCommand {
    @Option(help: "The file to read from.", completion: .file())
    var input: String

    @Option(help: "The output directory.", completion: .directory)
    var outputDir: String

    @Option(help: "The preferred file format.", completion: .list(["markdown", "rst"]))
    var format: String

    enum CompressionType: String, CaseIterable, ExpressibleByArgument {
        case zip, gzip
    }

    @Option(help: "The compression type to use.")
    var compression: CompressionType
}

The generated completion script will suggest only file names for the --input option, only directory names for --output-dir, and only the strings markdown and rst for --format. The --compression option uses the default completions for a CaseIterable type, so the completion script will suggest zip and gzip.

You can define the default completion kind for custom ExpressibleByArgument types by implementing defaultCompletionKind. For example, any arguments or options with this File type will automatically use files for completions:

struct File: Hashable, ExpressibleByArgument {
    var path: String

    init?(argument: String) {
        self.path = argument
    }

    static var defaultCompletionKind: CompletionKind {
        .file()
    }
}

For even more control over the suggested completions, you can specify a function that will be called during completion by using the .custom completion kind.

func listExecutables(_ arguments: [String]) -> [String] {
    // Generate the list of executables in the current directory
}

struct SwiftRun {
    @Option(help: "The target to execute.", completion: .custom(listExecutables))
    var target: String?
}

In this example, when a user requests completions for the --target option, the completion script runs the SwiftRun command-line tool with a special syntax, calling the listExecutables function with an array of the arguments given so far.

See Also

Shell Completion Scripts

Generating and Installing Completion Scripts

Install shell completion scripts generated by your command-line tool.

struct CompletionKind

The type of completion to use for an argument or option.

Current page is Customizing Completions

| |

OptionGroup Overview

Skip Navigation

Structure

OptionGroup

A wrapper that transparently includes a parsable type.

@propertyWrapper
struct OptionGroup<Value> where Value : ParsableArguments

OptionGroup.swift

Overview

Use an option group to include a group of options, flags, or arguments declared in a parsable type.

struct GlobalOptions: ParsableArguments {
    @Flag(name: .shortAndLong)
    var verbose: Bool

    @Argument var values: [Int]
}

struct Options: ParsableArguments {
    @Option var name: String
    @OptionGroup var globals: GlobalOptions
}

The flag and positional arguments declared as part of GlobalOptions are included when parsing Options.

Topics

Creating an Option Group

init(title: String, visibility: ArgumentVisibility)

Creates a property that represents another parsable type, using the specified title and visibility.

Option Group Properties

var title: String

The title to use in the help screen for this option group.

Infrequently Used APIs

init()

Creates a property that represents another parsable type.

Deprecated

var wrappedValue: Value

The value presented by this property wrapper.

var description: String

Default Implementations

API Reference\ CustomStringConvertible Implementations

Relationships

Conforms To

  • Swift.Copyable
  • Swift.CustomStringConvertible
  • Swift.Decodable
  • Swift.Sendable

See Also

Arguments, Options, and Flags

Declaring Arguments, Options, and Flags

Use the @Argument, @Option and @Flag property wrappers to declare the command-line interface for your command.

struct Argument

A property wrapper that represents a positional command-line argument.

struct Option

A property wrapper that represents a command-line option.

struct Flag

A property wrapper that represents a command-line flag.

protocol ParsableArguments

A type that can be parsed from a programs command-line arguments.

Current page is OptionGroup

| |

ArgumentParser Flag

Skip Navigation

Instance Property

wrappedValue

The value presented by this property wrapper.

var wrappedValue: Value { get set }

Flag.swift

Current page is wrappedValue

| |

chooseLast Flag

Skip Navigation

Type Property

chooseLast

The last enumeration case that is provided is used.

static var chooseLast: FlagExclusivity { get }

Flag.swift

Current page is chooseLast

| |

Exclusive Flag Usage

Skip Navigation

Type Property

exclusive

Only one of the enumeration cases may be provided.

static var exclusive: FlagExclusivity { get }

Flag.swift

Current page is exclusive

| |

ValidationError Message

Skip Navigation

Instance Property

message

The error message represented by this instance, this string is presented to the user when a ValidationError is thrown from either; run(), validate() or a transform closure.

var message: String { get }

Errors.swift

Current page is message

| |

Swift Argument Parser

Skip Navigation

Type Method

main()

Executes this command, or one of its subcommands, with the programs command-line arguments.

static func main()

ParsableCommand.swift

Discussion

Instead of calling this method directly, you can add @main to the root command for your command-line tool.

This method parses an instance of this type, one of its subcommands, or another built-in ParsableCommand type, from command-line arguments, and then calls its run() method, exiting with a relevant error message if necessary.

See Also

Starting the Program

static func main([String]?)

Executes this command, or one of its subcommands, with the given arguments.

Current page is main()

| |

Extended Grapheme Initializer

Skip Navigation

Initializer

init(extendedGraphemeClusterLiteral:)

Inherited from ExpressibleByStringLiteral.init(extendedGraphemeClusterLiteral:).

ArgumentParserSwift

init(extendedGraphemeClusterLiteral value: Self.StringLiteralType)

Available when ExtendedGraphemeClusterLiteralType is Self.StringLiteralType.

Current page is init(extendedGraphemeClusterLiteral:)

| |

ArgumentHelp Initializer

Skip Navigation

Initializer

init(stringLiteral:)

Inherited from ExpressibleByStringLiteral.init(stringLiteral:).

init(stringLiteral value: String)

ArgumentHelp.swift

Current page is init(stringLiteral:)

| |

Swift run() Method

Skip Navigation

Instance Method

run()

Inherited from ParsableCommand.run().

mutating func run() throws

ParsableCommand.swift

Current page is run()

| |

FlagInversion Operator

Skip Navigation

Operator

!=(_:_:)

Inherited from Equatable.!=(_:_:).

ArgumentParserSwift

static func != (lhs: Self, rhs: Self) -> Bool

Current page is !=(_:_:)

| |

Argument Help Initializer

Skip Navigation

Initializer

init(_:discussion:valueName:visibility:)

Creates a new help instance.

init(
    _ abstract: String = "",
    discussion: String = "",
    valueName: String? = nil,
    visibility: ArgumentVisibility = .default
)

ArgumentHelp.swift

Current page is init(_:discussion:valueName:visibility:)

| |

CustomStringConvertible Implementations

Skip Navigation

API Collection

CustomStringConvertible Implementations

Topics

Instance Properties

var description: String

Current page is CustomStringConvertible Implementations

| |

Grapheme Cluster Implementations

Skip Navigation

API Collection

ExpressibleByExtendedGraphemeClusterLiteral Implementations

Topics

Initializers

init(unicodeScalarLiteral: Self.ExtendedGraphemeClusterLiteralType)

Current page is ExpressibleByExtendedGraphemeClusterLiteral Implementations

| |

String Literal Implementations

Skip Navigation

API Collection

ExpressibleByStringLiteral Implementations

Topics

Initializers

init(extendedGraphemeClusterLiteral: Self.StringLiteralType)

init(stringLiteral: String)

Current page is ExpressibleByStringLiteral Implementations

| |