首先,声明一个类型来定义你需要从命令行收集的信息。使用 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 中的文档。
此仓库包含一些使用该库的示例
repeat
是上面显示的示例。roll
是一个简单的实用程序,实现为一个直线脚本。math
是使用嵌套命令和子命令的注释示例。count-lines
在其实现中使用了 async
/await
代码。你还可以看到 Swift 项目工具中 ArgumentParser
的应用示例
swift-format
使用了一些高级功能,例如自定义选项值和隐藏标志。swift-package-manager
包含一个深层的命令层次结构,并广泛使用选项组。Swift Argument Parser 包是源稳定的;版本号遵循语义版本控制。对公共 API 的源破坏性更改只能出现在新的主版本中。
swift-argument-parser
包 1.0.0 版本的公共 API 由 ArgumentParser
模块中标记为 public 的非下划线声明组成。不属于公共 API 的接口可能会在任何版本中继续更改,包括自动生成的帮助和错误消息的确切措辞和格式,以及包的示例、测试、实用程序和文档。
未来该软件包的次要版本可能会根据需要对这些规则进行更改。
我们希望这个包能够快速拥抱与它的任务相关的 Swift 语言和工具链改进。因此,我们预计这个包的新版本会不时要求客户端升级到更新的 Swift 工具链版本。需要新的 Swift 版本只会需要一个次要版本升级。
要在 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 |