dots Created with Sketch.
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.

amazon

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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
Modules and its Core features in JavaScriptJavaScriptAvoid using new Array() in JavaScriptJavaScriptRendering Elements in ReactReactHow to get the height and width of an element using JavaScript?JavaScriptHow to change HTML content on click using JavaScript?JavaScriptAlternate Style Sheets in CSSCSS