🔥 플래그 추가하기

188자
3분

이제 우리가 만들고 있는 도구에 --verbose 플래그를 추가해 보겠습니다. 사용자가 해당 옵션을 지정한 경우에만 메시지를 출력하도록 하는 거죠. 아래와 같이 동작하게 만들어 볼게요:

shell
% count --input-file readme.md --output-file readme.counts
(no output)
% count --verbose --input-file readme.md --output-file readme.counts
Counting words in 'readme.md' and writing the result into 'readme.counts'.
 
shell
% count --input-file readme.md --output-file readme.counts
(no output)
% count --verbose --input-file readme.md --output-file readme.counts
Counting words in 'readme.md' and writing the result into 'readme.counts'.
 

Count 구조체를 다음과 같이 변경해 보겠습니다:

swift
@main
struct Count: ParsableCommand {
    @Option var inputFile: String
    @Option var outputFile: String
    @Flag var verbose = false
 
    mutating func run() throws {
        if verbose {
            print("""
                Counting words in '\(inputFile)' \\
                and writing the result into '\(outputFile)'.
                """)
        }
 
        // 'inputFile'을 읽고, 단어를 세고, 'outputFile'에 저장합니다.
    }
}
 
swift
@main
struct Count: ParsableCommand {
    @Option var inputFile: String
    @Option var outputFile: String
    @Flag var verbose = false
 
    mutating func run() throws {
        if verbose {
            print("""
                Counting words in '\(inputFile)' \\
                and writing the result into '\(outputFile)'.
                """)
        }
 
        // 'inputFile'을 읽고, 단어를 세고, 'outputFile'에 저장합니다.
    }
}
 

@Flag 속성 래퍼는 --name처럼 생긴 명령줄 인자를 나타냅니다. 속성 이름에서 이름을 유추하죠. 플래그는 여기서 verbose 속성과 같이 대부분 Boolean 값으로 사용합니다.

@Flag 속성 래퍼를 사용하면 명령줄에서 --verbose와 같은 형식으로 플래그를 지정할 수 있습니다. 사용자가 해당 플래그를 지정하면 verbose 속성 값을 true로 설정합니다.

run() 메서드에서는 verbose 속성 값을 확인하여 메시지를 출력할지 여부를 결정합니다. verbosetrue이면 입력 파일과 출력 파일 이름을 포함한 메시지를 출력하는 거예요.

이렇게 플래그를 추가하면 사용자가 원할 때만 추가 정보를 출력하도록 할 수 있습니다. 간단하면서도 유용한 기능이 아닐까요?

YouTube 영상

채널 보기
입력을 전처리하는 Functor - Contravariant와 contramap 이해하기 | 프로그래머를 위한 카테고리 이론
함수 객체의 보편적 구성 | 프로그래머를 위한 카테고리 이론
Writer 펑터와 클라이슬리 카테고리 | 프로그래머를 위한 카테고리 이론
NestJS 커스텀 데코레이터 인자 전달 및 파이프 검증 활용법 | NestJS 가이드
C++ 속의 펑터 | 프로그래머를 위한 카테고리 이론
변환 파이프로 컨트롤러 코드 깔끔하게 만들기 | NestJS 가이드
class-validator 와 DTO | NestJS 가이드
NestJS 역할 기반 접근 권한 부여 - Guard, Reflector | NestJS 가이드