Swift – Read Number from Console Input
To read number from console input in Swift, use readLine() and Int() functions. readLine() function returns the string of characters read from standard input, and Int() converts this string to integer.
Converting to a number is not limited to converting the read string into an integer. We may also use Float(), Double(), etc., to convert the input into desired numeric type.
Examples
In the following example, we read a string from user, convert it into integer, and find its square.
main.swift
print("Enter a number (x) : ", terminator: "") if let input = readLine() { if let number = Int(input) { let result = number * number print("You entered \(number)") print("Its square = \(result)") } }
Output
Enter a number (x) : 4 You entered 4 Its square = 16! Program ended with exit code: 0
Enter a number (x) : 3 You entered 3 Its square = 9 Program ended with exit code: 0
Enter a number (x) : -2 You entered -2 Its square = 4 Program ended with exit code: 0
Now, we shall read a string from user, convert it into floating point value, and find its square.
main.swift
print("Enter a number (x) : ", terminator: "") if let input = readLine() { if let number = Float(input) { let result = number * number print("You entered \(number)") print("Its square = \(result)") } }
Output
Enter a number (x) : 1.2 You entered 1.2 Its square = 1.44 Program ended with exit code: 0
Conclusion
In this Swift Tutorial, we learned how to read a number from user using readLine() function and Int(), Float(), etc., with the help of examples.