To read multiple lines, we can just ask user for number of inputs and then in for loop or while loop we can read all those inputs. In fact, we can store it in array and do some maths like addition, subtraction etc.
import Foundation
print("How many inputs?n", terminator: "")
let size = Int(readLine()!)
if let size = size {
print("nEnter (size) Inputsn", terminator: "")
for index in 0...(size-1) {
print("nInput (index+1): ", terminator: "");
let number = Int(readLine()!)
if let number = number {
print("You entered: (number)")
}
}
}
//output
How many inputs?
2
Enter 2 Inputs
Input 1: 34
You entered: 34
Input 2: 56
You entered: 56
Also, like this following program, we can check whether the user has entered a specific word and if so, we can stop the program. Otherwise continue till infinite times.
import Foundation
print("Enter a word: (enter N to cancel)")
while let input = readLine() {
guard input != "N" else {
break
}
print("You entered: (input)")
print()
print("Enter a word: (enter N to cancel)")
}
//output
Enter a word: (enter N to cancel)
hello
You entered: hello
Enter a word: (enter N to cancel)
12
You entered: 12
Enter a word: (enter N to cancel)
n
You entered: n
Enter a word: (enter N to cancel)
N
Program ended with exit code: 0
I will discuss the Guard statement in future blog posts. For now just know that a guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
functions input readLine