Provides `initial` initializer parameter for input property wrappers
Description
Currently it's only possible to use initial value if the property type has a non-Optional type (by means of the wrappedValue parameter).
In some cases we might need to provide an optional default value, e.g when reading it from the environment.
To allow this we introduce the initial argument in the initializers of the Argument and Option property wrappers which do not contain the wrappedValue argument.
Resolves https://github.com/apple/swift-argument-parser/issues/556
Detailed Design
As an example, adding the initial parameter to the Option initializer:
public init(
name: NameSpecification = .long,
parsing parsingStrategy: SingleValueParsingStrategy = .next,
help: ArgumentHelp? = nil,
completion: CompletionKind? = nil,
initial: Value? = nil // <-- Using default value preserves backward compatibility
) {
self.init(_parsedValue: .init { key in
let arg = ArgumentDefinition(
container: Bare<Value>.self,
key: key,
kind: .name(key: key, specification: name),
help: help,
parsingStrategy: parsingStrategy.base,
initial: initial, // <-- injecting the initial value
completion: completion)
return ArgumentSet(arg)
})
would allow us to use it as follows:
@Option(initial: ProcessInfo.processInfo["REQUIRED_OPTION"])
var requiredOption: String
@Option(initial: ProcessInfo.processInfo["OPTIONAL_OPTION"])
var optionalOption: String?
The argument requirement therefore remains defined by it's nullability. A nil initial value in a non-Optional property would fail the command if the argument is not provided in the command line.
Documentation Plan
The initialzers' documentation has been updated.
Test Plan
Relevant tests added.
Source Impact
The change is backward-compatible.
Checklist
- [x] I've added at least one test that validates that my change is working, if appropriate
- [x] I've followed the code style of the rest of the project
- [x] I've read the Contribution Guidelines
- [x] I've updated the documentation if necessary
@tarbaiev-smg I believe you'd need to rebase your PR, since it now has conflicts that must be resolved.
@Coeur I'd be happy to, but first I'd like to get a confirmation that it still has a chance to be merged. It's been a year since I opened it.
@tarbayev I don't know.