Todd21
(Todd Heberlein)
1
Is there a way to pass a negative number as an option or command line argument to ArgumentParser?
For example, the code below generates an error when I try to pass a -5 as the optional value.
% ./parsetest2
num = 3
% ./parsetest2 --num 5
num = 5
%./parsetest2 --num -5
Error: Missing value for '--num <num>'
Help: --num <num> Specify a number as an option
Usage: print-number [--num <num>]
See 'print-number --help' for more information.
The code:
import Foundation
import ArgumentParser
struct PrintNumber: ParsableCommand {
@Option(help: "Specify a number as an option")
var num: Int = 3
func run() {
print("num = \(num)")
}
}
PrintNumber.main()
Todd21
(Todd Heberlein)
2
I have resolved it: Use the "=" sign
% ./parsetest2 --num=-5
num = -5
1 Like
Todd21
(Todd Heberlein)
3
Small observation along the same line as a negative number for an option: in the Math example code, the sequence of numbers for the argument must all be positive integers.
% ./parsetest3 add 4 3 5
12
% ./parsetest3 add 4 3 -5
Error: Unknown option '-5'
Usage: math add [--hex-output] [<values> ...]
See 'math add --help' for more information.
mayoff
(Rob Mayoff)
4
Does this work?
./parsetest3 add -- 4 3 -5
1 Like
MPLewis
(Mike Lewis)
5
To the best of my knowledge, in order to have negative numbers parsed in an array, you'll have to set the parsing strategy to .unconditionalRemaining:
...
@Argument(parsing: .unconditionalRemaining, ...)
var numbers: [Int]
...
1 Like
Todd21
(Todd Heberlein)
7
Yes! Adding this to my notes
% ./parsetest3 add -- 4 3 -5
2
Todd21
(Todd Heberlein)
8
No. neither single nor double quotes work. The equal and the negative number (without spaces) works.
% ./parsetest2 --num "-5"
Error: Missing value for '--num <num>'
Help: --num <num> Specify a number as an option
Usage: print-number [--num <num>]
./parsetest2 --num=-5
num = -5
Todd21
(Todd Heberlein)
9
This works too. Thanks!
@Argument(
parsing: .unconditionalRemaining,
help: "A group of integers to operate on.")
var values: [Int] = []
and then executing the code
% ./parsetest3 add 3 4 -5
2
% ./parsetest3 add -5 -4 -3
-12
1 Like
MPLewis
(Mike Lewis)
10
Unfortunately, quotes are processed at the shell level, so no program ever even sees the quotes you write and an Argument Parser executable can't make any parsing decisions based on that.
2 Likes