Featured image of post readLine() 알아보기

readLine() 알아보기

오늘은 스위프트에서 유저인풋을 받을 때 사용하는 readLine()에 대해 알아보자.

img

현재의 라인 혹은 EOF(End Of File) 까지의 표준입력을 받아 Optional String타입으로 반환하는 함수이다. 엔터가 입력될때까지 라고 이해하면 되겠다.

공백 단위로 입력받기

split

1
func split(separator: Character, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [Substring]

공백을 제거하고 입력받기 위해서는 split()함수를 이용하면 된다. [SubString] 타입으로 반환된다.

  • separator ➡️ 쪼개려는 문자 단위 " “(공백), “/”, etc
  • maxSplits ➡️ 지정한 문자 단위로 몇번까지 쪼갤지를 설정할 수 있다.
  • omittingEmptySubsequences ➡️ 비어있는 시퀀스 포함 유무 설정
1
2
3
4
5
6
if let input = readLine()?.split(seperator: " ") {
print(input)
}

// "a b c" 입력 시 " "(공백)기준으로 잘라서 배열로 저장한다.
// ["a" "b" "c"]

components

components(separatedBy: )를 사용할 수도 있다.

split과의 차이점은 Foundation 프레임워크가 정의되어 있어야 사용이 가능하고, 리턴값은 [String]

1
2
3
4
5
6
if let input = readLine()?.components(separatedBy: " ") {
print(input)
}

// "a b c" 입력 시 " "(공백)기준으로 잘라서 배열로 저장한다.
["a" "b" "c"]

두줄 입력 한꺼번에 받기

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
print("please input your firstName : ", terminator: "")
if let firstName = readLine() {

    print("please input your lastName : ", terminator: "")
    if let lastName = readLine()  {
        print(firstName, lastName)
    }
}

// please input your firstName : Jae
// please input your lastName : Kim
// Jae Kim

Reference

Swift Doc - readLine