🔥 최상위 명령어 정의하기
200자
2분
명령어와 하위 명령어로 구성된 프로그램을 만들기 위해서는 명령어 타입을 여러 개 정의한 후, 각 명령어 설정에서 하위 명령어를 지정해야 합니다. 예를 들어, 다음은 커맨드 라인에서 주어진 일련의 값에 대해 연산을 수행하는 math 유틸리티 인터페이스입니다.
shell
% math add 10 15 7
32
% math multiply 10 15 7
1050
% math stats average 3 4 13 15 15
10.0
% math stats average --kind median 3 4 13 15 15
13.0
% math stats
OVERVIEW: Calculate descriptive statistics.
USAGE: math stats <subcommand>
OPTIONS:
-h, --help Show help information.
SUBCOMMANDS:
average Print the average of the values.
stdev Print the standard deviation of the values.
quantiles Print the quantiles of the values (TBD).
See 'math help stats <subcommand>' for detailed help.
shell
% math add 10 15 7
32
% math multiply 10 15 7
1050
% math stats average 3 4 13 15 15
10.0
% math stats average --kind median 3 4 13 15 15
13.0
% math stats
OVERVIEW: Calculate descriptive statistics.
USAGE: math stats <subcommand>
OPTIONS:
-h, --help Show help information.
SUBCOMMANDS:
average Print the average of the values.
stdev Print the standard deviation of the values.
quantiles Print the quantiles of the values (TBD).
See 'math help stats <subcommand>' for detailed help.
먼저 최상위 Math 명령어를 정의해 볼게요. 명령어에는 하위 명령어와 기본 하위 명령어를 지정하는 정적 configuration 속성을 제공할 수 있어요.
swift
struct Math: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "A utility for performing maths.",
subcommands: [Add.self, Multiply.self, Statistics.self],
defaultSubcommand: Add.self)
}
swift
struct Math: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "A utility for performing maths.",
subcommands: [Add.self, Multiply.self, Statistics.self],
defaultSubcommand: Add.self)
}
Math는 Add, Multiply, Statistics 타입으로 세 개 하위 명령어를 나열했습니다. 그리고 Add를 기본 하위 명령어로 지정했어요. 이렇게 하면 사용자가 하위 명령어 이름을 생략했을 때 Add를 선택하죠.
shell
% math 10 15 7
32shell
% math 10 15 7
32










