dev._.note

[Swift] readLine() 본문

Dev/SWIFT

[Swift] readLine()

Laena 2023. 12. 2. 23:06

readLine()

 

readLine(strippingNewline:) | Apple Developer Documentation

Returns a string read from standard input through the end of the current line or until EOF is reached.

developer.apple.com

  • 모든 값을 optional string의 형태로 return 함(정수 입력은 int로 형변환)
  • enter = readLine() 
let text = readLine()!

 

split을 이용하여 한 줄로 여러 개를 입력

let arr = input.split(separator: " ")

 

let input = readLine()! // 1(띄어쓰기)2 입력
let arr = input.split(separator: " ") // 스페이스바를 기준으로 띄어쓰기
let A = Int(arr[0])! // split을 이용하여 나눈 수들을 arr 배열에 넣기
let B = Int(arr[1])! // arr에 들어있는 각각의 글자를 Int로 치환도 해줌
print(A + B) // 3 출력됨 

 

정수 입력받기

let num = Int(readLine()!)!

 

공백이 있는 숫자를 배열로 입력받기 (1 2 3 4 5)

let nums = readLine()!.split(separator: “ “).map{ Int($0) }
// nums = [1, 2, 3, 4, 5]

 

공백없는 숫자를 배열로 입력받기 (12345)

let nums = readLine()!.map{ Int(String($0))! }
// nums = [1, 2, 3, 4, 5]

 

reduce를 이용하면 입력받은 문자열 더하기

print(readLine()!.split(separator: " ").map { Int($0)! }.reduce(0,+))
// 입력: 1 2 3 4 5
// 출력: 15

 

for문

for i in 0..<Int(readLine()!)! {
    ...
}

 

'Dev > SWIFT' 카테고리의 다른 글

[Swift] 타입 캐스팅(Type Casting)  (2) 2023.12.05
[Swift] didSet 과 willSet  (0) 2023.12.04
[Swift] 계산기 만들기  (0) 2023.12.01
[Swift] 초기화(Initialization)  (1) 2023.11.30
[Swift] 상속(Inheritance)  (0) 2023.11.30