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
EasyWrite 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]!
Cheat sheet
To read user input in Swift, use the readLine() function:
let input = readLine()readLine() returns an optional String (String?) because the input might be empty or unavailable. Use if let to safely unwrap the optional before using the value:
if let name = readLine() {
print("Hello, \(name)!")
}Try it yourself
func greetUser(name: String) -> String {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input