Ad space (banner)
๐ŸฆSwift Lessons
Lesson 58 / 68

Reading from Standard Input

In this lesson you will learn how to read standard input with readLine() in Swift, so your program can respond to what a user types. This is for anyone searching for "Swift readLine how to use".

readLine() reads one line of input from the keyboard or another source. Use it when a command-line tool needs the user to type something.

The sample code prompts without a newline using print("Enter your name: ", terminator: ""), then receives the typed text safely with if let name = readLine() and uses it in a greeting.

A common stumbling block for beginners is that readLine() returns an Optional. Pairing it with if let to receive it safely is the idiomatic Swift approach, and without that it is easy to crash on a force unwrap.

In real-world development, using input without validating it can lead to unexpected errors, so pairing it with a validation step is safer.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)