Skip to content
Sign upLog in
← Back to Community

Swift input

Profile icon
IlonaKabbe

How do I add input from the console that the user types in and turn it into an integer in swift?

Voters
Profile icon
makarenkoj
Profile icon
coolnash
Profile icon
IlonaKabbe
Comments
hotnewtop
Profile icon
NDcoder

Use This:
var intInput = Int(readLine() ?? "0")!
print(intInput + 2)
Or, if you want to first make sure that it can be turned into an Integer:
if let intInput = Int(readLine() ?? "0"){ print(intInput + 2) }
These solutions also makes sure that the user actually types something in and doesn't just press the enter button right away.

Profile icon
theangryepicbanana

try something like

var input = Int(readLine()!)!

(there are !s because the input is an optional type by default, and Int wouldn't work without it)