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)")


How many inputs?

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 {
    print("You entered: (input)")
    print("Enter a word: (enter N to cancel)")


Enter a word: (enter N to cancel)
You entered: hello

Enter a word: (enter N to cancel)
You entered: 12

Enter a word: (enter N to cancel)
You entered: n

Enter a word: (enter N to cancel)
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 check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to create a multisite network in WordPress?WordPressWordPress: How to add a Search Icon in Menus with toggle effect using jQuery?jQueryGap in Flex?CSSA complete guide to add responsive YouTube videos using HTML and CSSCSSVariables and Distance Functions in SCSS (Sass)SCSSWhat is a Strict Requirement in PHP 7 Function Declarations?PHP