用于 Swift 的简单配置文件解析。
首先,声明一个包含配置选项的类型
struct Configuration: ParsableConfiguration {
enum Power: Int, Decodable {
case low, medium, high
}
@Option(
summary: "The power level used if not otherwise specified.",
discussion: """
When setting a default power level, it is crucial that you \
are sure that the consumption will not exceed the daily \
allocated allowance. Failure to keep within your usage \
limits will result in termination of the contract.
It's recommended that you do not change this value unless \
you are fully aware of the risks involved.
"""
)
var defaultPowerLevel: Power = .medium
@Option(summary: "Array of preferred spoken languages")
var preferredLanguages: [String] = ["en", "fr", "ar"]
@Option(.deprecated("Replaced by ‘preferredLanguages‘"), hidden: true)
var preferredLanguage: String? = nil
@Option(summary: "Details of the author used when creating commits")
var author: Author
struct Author: ParsableConfiguration {
@Option(summary: "The full name of the author")
var name: String = "John Doe"
@Option(summary: "The email address of the author")
var email: String = "no-reply@example.com"
}
}
然后使用通过 ParsableConfiguration
协议提供的静态方法,从适当的来源加载您的配置
// The default configuration instance
let configuration = Configuration.default
// Load directly from a file
let fileURL = URL(fileURLWithPath: "./.options.json")
let configuration = try Configuration.parse(contentsOf: fileURL)
// Load from data
let data = try downloadConfigurationFromServer()
let configuration = try Configuration.parse(data)
JSONDecoder
,但您可以插入任何内容有关示例,请参阅简单的 示例包 或 在 CreateAPI 中的用法。
深受 swift-argument-parser 的启发。