Playground는 input을 지원하지 않기 때문에 Xcode를 이용하여
Command Line Tool 프로젝트를 생성 후 코드를 실행해야 한다.
readLine()함수를 이용하여 콘솔창으로 입력을 받을 수 있다.
Optional<String>으로 반환된다.let a = readLine() //5
print(type(of: a)) //Optional<String>
let unwrappingA = a!
print(type(of: unwrappingA)) //String
let intA = Int(unwrappingA)
print(type(of: intA)) //Optional<Int>
let intUnwrappingA = intA!
print(type(of: intUnwrappingA)) //Int
다음과 같이 축약이 가능하다.
let a = Int(readLine()!)!
split()을 이용하여 공백을 기준으로 문자열 자르기가 가능하다.
let name = readLine()! //n a m e
print(type(of: name)) //String
let splitName = name.split(separator: " ")
print(type(of: splitName)) //Array<Substring>
let closerSplitName = splitName.split { $0 == " " } //클로저 이용
print(type(of: closerSplitName)) //Array<Substring>
Split()은 Array<Substring>을 반환하기 때문에 String으로 사용하기 위해선 String으로 형변환을 해주어야 한다.components()를 이용해 Array<Substring>이 아닌 Array<String>을 반환받을 수 있다.
import Foundation
let name = readLine()! //n a m e
print(type(of: name)) //String
let comName = name.components(separatedBy: " ")
print(type(of: comName)) //Array<String>
Array<String>을 반환받을 수 있다.split()과 달리 components()는 Foundation을 import해줘야 사용이 가능하다.map과 클로저를 이용한다.
let vars = readLine()!.split(separator: " ").map { Int(String($0))! }
print(type(of: vars))
Int($0)! 보다 Int(String($0))!의 속도가 좀 더 빠르다고함readLine()을 여러번 쓴다.
let a = readLine()
let b = readLine()
print(a, b)
엔터를 칠때마다 하나의 readLine()입력이 완료된다.
1, 2, 3, 4, 5를 12345처럼 연속적으로 입력받을때 배열로 먼저 변환하여 처리한다.
let vars = Array(readLine()!) //12345
print(vars) //["1", "2", "3", "4", "5"]
print(type(of: vars)) //Array<Character>
let intVars = vars.map { Int(String($0))! }
print(intVars) //[1, 2, 3, 4, 5]
print(type(of: intVars)) //Array<Int>
let a = Int(readLine())!`
let a = readLine()!.split(separator: " ").map { Int(String($0))! }
let a = readLine()!
let a = readLine()!.split(separator: " ")
let b = readLine()!.split { $0 == " " }
let a = Array(readLine()!).map { Int(String($0))! }
파이썬 하다가 스위프트보니 어질어질 하네요....