YogeshChauhan . com

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.

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 5 Use inline if to make a shorter conditional syntax in React May 4 What is Conditional Rendering in React? May 3 How does @extend rule work in SCSS (Sass)? May 2 How different is Handling Events in React vs HTML DOM? May 2 How to create bouncing balls using HTML canvas and JavaScript? Apr 30 HTML canvas methods

You might also like these

A Step by Step Guide to Make RSS in XML For Any Website or Blog For FreeMiscA complete diagram with building blocks of an Angular applicationAngularStyling Lists with CSSCSSHow to remove special characters (dash, asterisk etc) from any string in PHP?PHPHow to hide a DIV on clicks outside of it using jQuery?jQueryHow to Pop an Alert Box in PHP?JavaScript