Convert Figma logo to code with AI

apple logoswift-argument-parser

Straightforward, type-safe argument parsing for Swift

3,308
311
3,308
91

Top Related Projects

13,987

A full featured, fast Command Line Argument Parser for Rust

7,933

Create *beautiful* command-line interfaces with Python

3,478

CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser

37,507

A Commander for modern Go CLI interactions

go command line option parser

Quick Overview

Swift Argument Parser is a library for parsing command-line arguments in Swift applications. It provides a declarative API that allows developers to define command-line interfaces using Swift's property wrappers, making it easy to create robust and user-friendly command-line tools.

Pros

  • Easy to use with a declarative syntax
  • Automatic generation of help and error messages
  • Support for subcommands and nested command structures
  • Type-safe argument parsing

Cons

  • Limited to Swift applications
  • May have a steeper learning curve for developers new to property wrappers
  • Less flexible than some lower-level argument parsing libraries

Code Examples

  1. Basic command with arguments:
import ArgumentParser

struct Greet: ParsableCommand {
    @Argument(help: "The name of the person to greet.")
    var name: String

    @Option(name: .shortAndLong, help: "The number of times to greet.")
    var count: Int = 1

    func run() throws {
        for _ in 0..<count {
            print("Hello, \(name)!")
        }
    }
}

Greet.main()
  1. Subcommand example:
import ArgumentParser

struct Math: ParsableCommand {
    static var configuration = CommandConfiguration(
        subcommands: [Add.self, Subtract.self])
}

struct Add: ParsableCommand {
    @Argument var numbers: [Int]

    func run() {
        print(numbers.reduce(0, +))
    }
}

struct Subtract: ParsableCommand {
    @Argument var numbers: [Int]

    func run() {
        print(numbers.dropFirst().reduce(numbers[0], -))
    }
}

Math.main()
  1. Flag example:
import ArgumentParser

struct Example: ParsableCommand {
    @Flag(name: .shortAndLong, help: "Enable verbose mode.")
    var verbose = false

    func run() throws {
        if verbose {
            print("Verbose mode enabled")
        }
        print("Hello, world!")
    }
}

Example.main()

Getting Started

To use Swift Argument Parser in your project:

  1. Add the package to your Package.swift file:
dependencies: [
    .package(url: "https://github.com/apple/swift-argument-parser", from: "1.2.0"),
],
targets: [
    .target(
        name: "YourTarget",
        dependencies: [
            .product(name: "ArgumentParser", package: "swift-argument-parser"),
        ]),
]
  1. Import the library in your Swift file:
import ArgumentParser
  1. Define your command structure and implement the ParsableCommand protocol.

  2. Call YourCommand.main() to run your command-line tool.

Competitor Comparisons

13,987

A full featured, fast Command Line Argument Parser for Rust

Pros of clap

  • More mature and feature-rich, with a longer development history
  • Supports both declarative and builder patterns for flexibility
  • Extensive documentation and examples available

Cons of clap

  • Steeper learning curve due to more complex API
  • Larger binary size and longer compilation times
  • Rust-specific, limiting cross-language usage

Code Comparison

Swift Argument Parser:

struct Example: ParsableCommand {
    @Argument(help: "The name to greet")
    var name: String

    func run() throws {
        print("Hello, \(name)!")
    }
}

clap:

use clap::Parser;

#[derive(Parser)]
struct Cli {
    name: String,
}

fn main() {
    let cli = Cli::parse();
    println!("Hello, {}!", cli.name);
}

Both libraries offer declarative approaches to defining command-line interfaces, but clap provides more options for customization and advanced use cases. Swift Argument Parser focuses on simplicity and ease of use, making it quicker to get started for Swift developers. clap's extensive feature set and flexibility come at the cost of a steeper learning curve and more complex setup for basic use cases.

7,933

Create *beautiful* command-line interfaces with Python

Pros of docopt

  • Language-agnostic approach, supporting multiple programming languages
  • Defines CLI interface using a simple and readable help message format
  • Minimal setup required, with a concise syntax for defining options and arguments

Cons of docopt

  • Less flexibility for complex command structures or nested subcommands
  • Limited built-in validation and type conversion capabilities
  • Maintenance and updates may be less frequent compared to Swift Argument Parser

Code Comparison

docopt:

"""Naval Fate.

Usage:
  naval_fate ship <name> move <x> <y> [--speed=<kn>]
  naval_fate ship shoot <x> <y>
  naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate -h | --help
  naval_fate --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.
"""

Swift Argument Parser:

struct NavalFate: ParsableCommand {
    static var configuration = CommandConfiguration(
        subcommands: [Ship.self, Mine.self])

    struct Ship: ParsableCommand {
        @Argument var name: String
        @Argument var x: Int
        @Argument var y: Int
        @Option var speed: Int = 10
    }

    struct Mine: ParsableCommand {
        @Argument var action: Action
        @Argument var x: Int
        @Argument var y: Int
        @Flag var moored: Bool = false
        @Flag var drifting: Bool = false

        enum Action: String, ExpressibleByArgument {
            case set, remove
        }
    }
}
3,478

CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser

Pros of Kingpin

  • More mature and battle-tested, with a longer history of use in production environments
  • Supports both Go and Python, offering flexibility for multi-language projects
  • Provides a more extensive set of built-in features, including support for environment variables and configuration files

Cons of Kingpin

  • Less idiomatic Swift syntax compared to Swift Argument Parser
  • May have a steeper learning curve for developers new to command-line argument parsing
  • Not as tightly integrated with the Swift ecosystem and tooling

Code Comparison

Swift Argument Parser:

struct Example: ParsableCommand {
    @Argument(help: "The name to greet")
    var name: String

    func run() throws {
        print("Hello, \(name)!")
    }
}

Kingpin:

var (
    name = kingpin.Arg("name", "The name to greet").Required().String()
)

func main() {
    kingpin.Parse()
    fmt.Printf("Hello, %s!\n", *name)
}

Both libraries offer declarative syntax for defining command-line arguments, but Swift Argument Parser leverages Swift's property wrappers for a more concise and type-safe approach. Kingpin uses a more traditional method of defining arguments and flags, which may be more familiar to developers coming from other languages.

37,507

A Commander for modern Go CLI interactions

Pros of Cobra

  • Written in Go, offering cross-platform compatibility and easy deployment
  • Extensive documentation and a large community, providing robust support
  • Supports nested subcommands, allowing for complex CLI structures

Cons of Cobra

  • More verbose syntax compared to Swift Argument Parser
  • Requires more boilerplate code for basic command setup
  • Less integrated with the language's standard library

Code Comparison

Swift Argument Parser:

struct Example: ParsableCommand {
    @Argument(help: "The name to greet")
    var name: String

    func run() throws {
        print("Hello, \(name)!")
    }
}

Cobra:

var rootCmd = &cobra.Command{
    Use:   "greet",
    Short: "A brief description of your application",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Printf("Hello, %s!\n", args[0])
    },
}

Key Differences

  • Swift Argument Parser uses a more declarative approach with property wrappers
  • Cobra relies on a more imperative style with function-based command definitions
  • Swift Argument Parser integrates tightly with Swift's type system
  • Cobra offers more flexibility in terms of command structure and organization

Both libraries provide powerful CLI creation capabilities, but Swift Argument Parser is more tailored for Swift development, while Cobra offers a versatile solution for Go projects.

go command line option parser

Pros of go-flags

  • More mature and established project with a longer history
  • Supports a wider range of programming paradigms (e.g., struct tags, reflection)
  • Offers more flexible option handling, including short and long options

Cons of go-flags

  • Less idiomatic Go code compared to swift-argument-parser's Swift-native approach
  • May require more boilerplate code for complex command structures
  • Documentation is less comprehensive and user-friendly

Code Comparison

swift-argument-parser:

struct Example: ParsableCommand {
    @Argument(help: "The name to greet.")
    var name: String

    func run() throws {
        print("Hello, \(name)!")
    }
}

go-flags:

type Options struct {
    Name string `short:"n" long:"name" description:"The name to greet"`
}

var opts Options
parser := flags.NewParser(&opts, flags.Default)
_, err := parser.Parse()
if err == nil {
    fmt.Printf("Hello, %s!\n", opts.Name)
}

Both libraries aim to simplify command-line argument parsing, but they take different approaches. swift-argument-parser focuses on a declarative, Swift-native style, while go-flags offers more flexibility at the cost of some additional complexity. The choice between them depends on the specific needs of the project and the developer's preferences for API design and language idioms.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Swift Argument Parser

Usage

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 ArgumentParser's property wrappers, and then declare conformance to ParsableCommand and add the @main attribute. (Note, for async renditions of run, conform to AsyncParsableCommand rather than ParsableCommand.) Finally, implement your command's logic in the run() method.

import ArgumentParser

@main
struct Repeat: ParsableCommand {
    @Flag(help: "Include a counter with each repetition.")
    var includeCounter = false

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

    @Argument(help: "The phrase to repeat.")
    var phrase: String

    mutating func run() throws {
        let repeatCount = count ?? 2

        for i in 1...repeatCount {
            if includeCounter {
                print("\(i): \(phrase)")
            } else {
                print(phrase)
            }
        }
    }
}

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

ArgumentParser uses your properties' names and type information, along with the details you provide using property wrappers, to supply useful error messages and detailed help:

$ repeat hello --count 3
hello
hello
hello
$ repeat --count 3
Error: Missing expected argument 'phrase'.
Help:  <phrase>  The phrase to repeat.
Usage: repeat [--count <count>] [--include-counter] <phrase>
  See 'repeat --help' for more information.
$ repeat --help
USAGE: repeat [--count <count>] [--include-counter] <phrase>

ARGUMENTS:
  <phrase>                The phrase to repeat.

OPTIONS:
  --include-counter       Include a counter with each repetition.
  -c, --count <count>     The number of times to repeat 'phrase'.
  -h, --help              Show help for this command.

Documentation

For guides, articles, and API documentation see the library's documentation on the Web or in Xcode.

Examples

This repository includes a few examples of using the library:

  • repeat is the example shown above.
  • roll is a simple utility implemented as a straight-line script.
  • math is an annotated example of using nested commands and subcommands.
  • count-lines uses async/await code in its implementation.

You can also see examples of ArgumentParser adoption among Swift project tools:

  • swift-format uses some advanced features, like custom option values and hidden flags.
  • swift-package-manager includes a deep command hierarchy and extensive use of option groups.

Project Status

The Swift Argument Parser package is source-stable; version numbers follow semantic versioning. Source-breaking changes to public API can only land in a new major version.

The public API of version 1.0.0 of the swift-argument-parser package consists of non-underscored declarations that are marked public in the ArgumentParser module. Interfaces that aren't part of the public API may continue to change in any release, including the exact wording and formatting of the autogenerated help and error messages, as well as the package’s examples, tests, utilities, and documentation.

Future minor versions of the package may introduce changes to these rules as needed.

We want this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. Requiring a new Swift release will only require a minor version bump.

Adding ArgumentParser as a Dependency

To use the ArgumentParser library in a SwiftPM project, add it to the dependencies for your package and your command-line executable target:

let package = Package(
    // name, platforms, products, etc.
    dependencies: [
        // other dependencies
        .package(url: "https://github.com/apple/swift-argument-parser", from: "1.3.0"),
    ],
    targets: [
        .executableTarget(name: "<command-line-tool>", dependencies: [
            // other dependencies
            .product(name: "ArgumentParser", package: "swift-argument-parser"),
        ]),
        // other targets
    ]
)

Supported Versions

The most recent versions of swift-argument-parser support Swift 5.5 and newer. The minimum Swift version supported by swift-argument-parser releases are detailed below:

swift-argument-parserMinimum Swift Version
0.0.1 ..< 0.2.05.1
0.2.0 ..< 1.1.05.2
1.1.0 ..< 1.3.05.5
1.3.0 ...5.7