Menu
Coddy logo textTech

ReadLine Input

Part of the Fundamentals section of Coddy's Swift journey. Lesson 33 of 86.

So far, your programs have used hardcoded values. To make programs interactive, you need to accept input from the user. In Swift, the readLine() function reads a line of text from standard input.

let input = readLine()
print(input)

There's an important detail here: readLine() returns an optional String (String?), not a regular String. This is because the input might be empty or unavailable. You'll need to unwrap it safely before using the value:

if let name = readLine() {
    print("Hello, \(name)!")
}

Using if let ensures you only work with the input when it actually contains a value. This pattern of reading input and safely unwrapping it is something you'll use frequently when building interactive programs.

challenge icon

Challenge

Easy
Write a function greetUser that takes name and returns a personalized greeting message.

The function simulates what you would do after safely unwrapping input from readLine(). Given a name, construct and return a greeting string.

Parameters:

  • name (String): The user's name

Returns: A greeting in the format: Hello, [name]!

Try it yourself

func greetUser(name: String) -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Swift playground