Swift Program to Get Input from the User


Getting input from the user in Swift is very easy with the help of the readLine() function. This function returns a string of characters which is read from the standard input at the end of the current line. If the control is already reached the EOF when the readLine() function is called then this method will return nil.

Syntax

Following is the syntax of Swift readLine() function −

readLine(strippingNewline: true)
Or 
readLine()

Reading integer

Example

The following program shows how to get input from the user.

import Foundation import Glibc print("Please enter number 1") var num1 = Int(readLine()!)! print("Please enter number 2") var num2 = Int(readLine()!)! var sum = num1 + num2 print("The sum of \(num1) and \(num2) is \(sum)")

Input

Please enter number 1
10
Please enter number 2
20

Output

The sum of 10 and 20 is 30

Here in the above code, we take two integer type inputs from the user with the help of the readLine() function. As we knew that the readLine() function returns a string so we use Int() function to convert the string into integer as shown in the below code −

var num1 = Int(readLine()!)!

Display the sum of the given numbers that is 10 + 20 = 30.

Reading String

Example

The following program shows how to get input from the user.

import Foundation import Glibc print("Please enter your favourite subject: ") if let inputData = readLine() { print("Subject is \(inputData)!") }

STDIN Input

Please enter your favourite subject: 
C++

Output

Subject is C++!

Here in the above code, user entered his/her favourite subject using the readLine() function. And display the entered subject using the below code −

if let inputData = readLine() {
   print("Subject is \(inputData)!")
}

Where the inputData variable stores the value of readLine() function and display the output that is “Subject is C++!”.

Updated on: 05-Aug-2022

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements