Swift User Input
User input is text a person types while a program runs. The readLine function reads one typed line and gives it back as an optional string.
Reading a name
The program prints a prompt and reads one line, and the typed line here is Ana. The greeting uses that name, with a fallback word held ready.
print("Name?")
let name = readLine()
print("Hello, \(name ?? "stranger")")Reading a number as text
The typed line here is 30, and it arrives as text. Two if let steps open the line and then the Int, and the print shows the number doubled.
print("Age?")
let line = readLine()
if let line = line {
if let age = Int(line) {
print(age * 2)
}
}No line arrives
This run gets no typed line at all, so readLine gives nil. The fallback word stranger takes its place in the greeting.
print("Name?")
let name = readLine()
print("Hello, \(name ?? "stranger")")Example
print("Name?")
let name = readLine() ?? "stranger"
print("Hello, \(name)")
print("Age?")
if let line = readLine() {
if let age = Int(line) {
print(age * 2)
}
}Key points
- readLine reads one line of typed text.
- readLine gives back an optional string, since the typed line may never arrive.
- A prompt printed before the read tells the person what to type.
- The ?? operator can swap a missing line for a fallback word.
- Turning typed text into an Int gives an optional, so if let opens it before use.
- Each readLine call reads the next line of input.
In this example, the program prints the Name prompt and reads the first typed line, which is Ana. The greeting prints with that name, falling back to stranger only if no line arrives. The program then prints the Age prompt, reads the second line 30 as text, opens it as an Int with if let, and prints the number doubled to 60.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What type does readLine give back?