Yogesh Chauhan's Blog

Reading Multiple Inputs in Swift

in Swift on March 6, 2020

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.


Most Read

#1 How to add Read More Read Less Button using JavaScript? #2 How to check if radio button is checked or not using JavaScript? #3 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to get Current Year, Month and Date in JavaScript?JavaScriptSQL ANY OperatorSQL/MySQLUseful (and probably ignored) HTML tags: Part 1HTMLSlider animation using CSS transform propertyCSSWhat is HTMLUnknownElement?HTMLCREATE TABLE Examples in PostgreSQLPostgres