Ask coding questions

← Back to all posts
how to take user input in the form of an integer
AaronPhilip (4)

Please help me. This is so irritating like i just want to take two integers and add them. Instead, it takes it in the form of a string and just concatenates them.

Thank you.

Answered by Coder100 (17039) [earned 5 cycles]
View Answer
Coder100 (17039)

Hello, to do this, you will have to use the Int class:

print("Enter a number")
var a = readLine()!
var aint = Int(a) ?? 0

print("Enter another number")
var b = readLine()!
var bint = Int(b) ?? 0

var ans = aint + bint

Note the ??. This is because if the user input was a, you wouldn't be able to convert it to a number and the variable would become null iirc.

AaronPhilip (4)

@Coder100 Thank you :) it helped a lot

PattanAhmed (1397)

@AaronPhilip Hi,
It's easy...
You just have to convert it into Int data type
Here is your code with explanation:-

// Taking input of first number and converting it into a Int Data Type
print("Enter first number: ")
var number = readLine()!
var converting = Int(number) ?? 0

// Taking input of second number and converting it into a Int Data Type
print("Enter second number: ")
var number1 = readLine()!
var converting1 = Int(number1) ?? 0

// Adding the both inputs
var result = converting + converting1;

// Printing the output

That's it

Hope this helps

PattanAhmed (1397)

@AaronPhilip Welcome!
Happy to help you.

Please mark my answer if that helps

GoodCoderBadBoy (2)

I've never used swift before, but looking things up, you may need to convert the readline() output into an int. I may be totally and utterly wrong though.

print("Enter a number")
var a=Int(readLine())!
print("Enter another number")
var b=Int(readLine())!
var ans=a+b
Coder100 (17039)

not quite, you forgot to handle the cases when the input isn't an integer @GoodCoderBadBoy