Reading Multiple Inputs in Swift
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.


Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS Mar 2 WordPress: How to access first and random row values from a repeater field in ACF? Mar 1 The basics of CSS Box model Feb 27 WordPress: How to display slider repeater fields in ACF? Feb 26 Simple Page Hit Counter in PHP

You might also like these

How to get query string values in JavaScript? (URL Manipulation using URLSearchParams)JavaScriptALTER DATABASE in PostgreSQLPostgresHere’s what we can do with PHP date() functionPHPHow to solve “framework not found” error in Swift?SwiftCanvas Drawing in HTML5HTMLthe box-sizing property in CSSCSS