🔥 도움말 제공하기

223자
3분

ArgumentParser는 사용자가 -h 또는 --help 플래그를 사용하면 모든 명령에 대한 도움말을 자동 생성합니다.

% count --help
USAGE: count --input <input> --output <output> [--verbose]
 
 
OPTIONS:
  -i, --input <input>
  -o, --output <output>
  -v, --verbose
  -h, --help              Show help information.
 
shell

이는 좋은 출발점입니다. 개발자가 정의한 모든 옵션 이름이 표시되고, 도움말에는 --input--output 옵션에 값이 필요하다는 걸 보여줍니다. 하지만 커스텀 옵션과 플래그에는 설명이 없습니다. 이제 문자열을 help 매개변수로 전달하여 설명을 추가해 봅시다.

@main
struct Count: ParsableCommand {
    // 입력 파일 경로를 받는 옵션
    @Option(name: [.short, .customLong("input")], help: "A file to read.")
    var inputFile: String
 
    // 출력 파일 경로를 받는 옵션
    @Option(name: [.short, .customLong("output")], help: "A file to save word counts to.")
    var outputFile: String
 
    // 자세한 출력 여부를 지정하는 플래그
    @Flag(name: .shortAndLong, help: "Print status updates while counting.")
    var verbose = false
 
    // 실제 코드가 실행되는 부분
    mutating func run() throws { ... }
}
 
swift

이제 도움말 화면이 각 매개변수에 대한 설명을 포함합니다.

% count -h
USAGE: count --input <input> --output <output> [--verbose]
 
 
OPTIONS:
  -i, --input <input>     A file to read.
  -o, --output <output>   A file to save word counts to.
  -v, --verbose           Print status updates while counting.
  -h, --help              Show help information.
 
shell

코드를 자세히 살펴보면 @Option@Flag 속성의 help 인자로 각 옵션과 플래그에 대한 설명을 제공했습니다. 이렇게 하면 사용자가 프로그램을 어떻게 사용해야 할지 더 잘 이해할 수 있겠죠?