Skip to content
AgileLogics
4 min read

Reading User Input

Prerequisites: Type conversion

In a command-line program, readLine() waits for the user to type a line and press Enter, then returns what they typed.

readLine() returns a String? — it's nil if there's no more input (for example, when input is piped from a file that has ended).

Example

print("What's your name? ", terminator: "")

if let name = readLine(), !name.isEmpty {
    print("Nice to meet you, \(name)!")
} else {
    print("No name entered.")
}

Expected output

What's your name? Ada
Nice to meet you, Ada!

(Ada is what the user typed.) if let can check several conditions separated by commas: here, that there was input and it isn't empty.

Reading numbers

Input is always text. Convert it, handling invalid input:

import Foundation

print("How old are you? ", terminator: "")
let line = readLine() ?? ""

guard let age = Int(line) else {
    print("Please enter a whole number.")
    exit(1)
}

print("In ten years you'll be \(age + 10).")

At the top level of a script, there's no function to return from, so this example uses exit(1) to stop the program — which is why it imports Foundation.

Note: Xcode playgrounds and SwiftUI apps don't read keyboard input this way. Run these examples as .swift files in a terminal.

Practice

Ask the user for their favorite color and print it back in capitals: BLUE is a great color!.

Show solution
print("Favorite color? ", terminator: "")
let color = readLine() ?? "no"
print("\(color.uppercased()) is a great color!")