Swift 参数解析器

使用方法

首先,声明一个类型来定义你需要从命令行收集的信息。使用 ArgumentParser 的属性包装器装饰每个存储的属性,然后声明遵循 ParsableCommand 协议,并添加 @main 属性。最后,在 run() 方法中实现你的命令逻辑。

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)
            }
        }
    }
}

ArgumentParser 库会解析命令行参数,实例化你的命令类型,然后执行你的 run() 方法,或者退出并显示有用的消息。

ArgumentParser 使用你的属性名称和类型信息,以及你使用属性包装器提供的详细信息,来提供有用的错误消息和详细的帮助信息。

$ 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.

文档

有关指南、文章和 API 文档,请参阅Web 上的库文档或 Xcode 中的文档。

示例

此仓库包含一些使用该库的示例

你还可以看到 Swift 项目工具中 ArgumentParser 的应用示例

项目状态

Swift Argument Parser 包是源稳定的;版本号遵循语义版本控制。对公共 API 的源破坏性更改只能出现在新的主版本中。

swift-argument-parser 包 1.0.0 版本的公共 API 由 ArgumentParser 模块中标记为 public 的非下划线声明组成。不属于公共 API 的接口可能会在任何版本中继续更改,包括自动生成的帮助和错误消息的确切措辞和格式,以及包的示例、测试、实用程序和文档。

未来该软件包的次要版本可能会根据需要对这些规则进行更改。

我们希望这个包能够快速拥抱与它的任务相关的 Swift 语言和工具链改进。因此,我们预计这个包的新版本会不时要求客户端升级到更新的 Swift 工具链版本。需要新的 Swift 版本只会需要一个次要版本升级。

添加 ArgumentParser 作为依赖项

要在 SwiftPM 项目中使用 ArgumentParser 库,请将其添加到你的软件包和命令行可执行目标的依赖项中。

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

支持的版本

最新版本的 swift-argument-parser 支持 Swift 5.5 及更高版本。 swift-argument-parser 版本支持的最低 Swift 版本在下面详细说明

swift-argument-parser 最低 Swift 版本
0.0.1 ..< 0.2.0 5.1
0.2.0 ..< 1.1.0 5.2
1.1.0 ... 5.5