Swift에서 커맨드라인으로 입력받고 조작하기

최대 1 분 소요

Swift에서 키보드, 커맨드라인(표준입력)으로 입력받는 방법

Swift에서는 표준입력 받는 함수를 readLine(strippingNewline:)으로 정의하고 있습니다. readLine() 함수는 다음과 같이 정의되었습니다.

func readLine(strippingNewline: Bool = true) -> String?

readline 함수는 입력을 받아서 문자열을 반환하는데 만약 파일의 끝에서 다시 한 번 호출할 경우 nil을 반환합니다.

strippingNewline 파라미터는 개행문자와 문자조합을 문자열에서 제거 여부를 나타냅니다. 디폴트로 true로 설정되어있으며 개행문자와 문자조합이 제거됩니다.

키보드에서 입력을 받으면 문자열 옵셔널이 반환되므로 옵셔널 바인딩을 통해 사용할 수 있습니다.

if let input = readLine() {
    print("input = \(input)")

이후 정수형 또는 실수형으로 변경하여 사용할 수 있습니다.

if let input = readLine() {
    print("input = \(input)")
    
    if let integer = Int(input) {
        print("integer = \(integer)")
    }
    
    if let double = Double(input) {
        print("double = \(double)")
    }

기본적으로 문자열이므로 split(separator:) 메서드를 통해 각각의 요소로 분리할 수 있습니다. split(separator:) 메서드의 반환 타입은 String.SubSequence 입니다.

if let input = readLine() {
    let splitString = input.split(separator: " ")
    print(splitString)
}

Foundation 프레임워크에 있는 components(separatedBy:) 메서드를 사용하여 위 메서드와 같이 각각의 요소로 분리할 수 있습니다. components(separatedBy:) 메서드의 반환 타입은 문자열 배열 [String] 입니다.

if let input = readLine() {
    let componentsString = input.components(separatedBy: " ")
    print(componentsString)
}

카테고리:

업데이트:

댓글남기기