Read Input from User in Swift via Command Line
To read input from user in Swift via command line, use readLine() function.
readLine() function returns a string read from standard input through the end of the current line or until EOF is reached.
In this tutorial, we will learn how to read input from user in Swift Command Line Application.
Swift Example
In this example, we will read the name of the user from console input, and we shall print the name to the output using print() statement.
main.swift
import Foundation
print("Enter your name : ", terminator:"")
let input = readLine()
print("Hello \(input!)")
When user runs this program, only the string "Enter you name : "
is printed to the console. Then, the user enters a string (his/her name) and enter return to mark the end of input. The input string is read to the variable input
. And we can programmatically use this value.
Program Output
Enter your name : ABC
Hello ABC
Summary
We have learnt how to read input from user in Swift Command Line Application.