Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 146 ยท Getting Started

Reading Input

Learn how to read input in Swift with readLine, turn text into numbers with Int(_:) and Double(_:), handle nil and bad input, and write small interactive programs.

Programs become interesting when they react to what someone types. In a Swift command-line program, the standard way to read a line of text from the keyboard (or from a file or another program piped into yours) is the function readLine(). It is deliberately small: it hands you one line as a String, or nil when there is nothing left to read. Everything else, such as turning text into numbers, checking that it makes sense and repeating until it does, you build from pieces you already know.

In this tutorial, every example that reads input has its input preset in the page (the "Program input" box), because a web page cannot wait for a keyboard the way a terminal can. You can edit the input box and run again. The same code works unchanged with a real terminal. This lesson builds on Optionals ideas, which we will introduce just enough here, and it uses Strings and Operators.

readLine returns an optional

readLine() returns String?. The result is nil at the end of the input (the user pressed Ctrl-D in a terminal, or a piped file ended) and otherwise the text of the next line, without the trailing newline.

Swift Reading lines with readLine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The two reads give Optional("Ada") and Optional("Lovelace"); the third has run out of lines and gives nil. The if let first, let last line unwraps both optionals at once (the short form if let first means if let first = first). The prompt text is printed with print, which ends with a newline; use print("Name: ", terminator: "") if you want the cursor to stay on the same line.

A program that is run without any input, such as a plain swift main.swift in a terminal that never gets a keystroke, waits at readLine() until a line arrives. In our runner the input is a fixed text, and when it is used up, readLine() returns nil immediately instead of waiting.

The force-unwrap shortcut

You will see readLine()! in tutorials and quick scripts. The ! says "I am sure this is not nil", and if it is nil, the program stops. That is acceptable in a throw-away script with known input and a bad idea anywhere else. It is worth seeing exactly what happens:

Swift Force-unwrapping nil at the end of input (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first read works. The second finds the input exhausted, and the program dies. The runner reports Program crashed: Illegal instruction (signal 4, SIGILL), which is how a Swift runtime trap looks on Linux. Two details are worth noticing. This optimized build prints no Fatal error: ... explanation, only a backtrace pointing into main. And the Got: only one line text, although it was printed before the crash, never appears: when standard output is not a terminal, print buffers its text, and a trap ends the process without flushing it. Lost output makes crashes harder to diagnose, which is one more reason to avoid !. We replace it with real checks in the next sections.

Turning text into numbers

Everything readLine() gives you is text. To do arithmetic you must convert, and the conversion can fail, which is why the number types have failable initializers: Int("42") gives Optional(42) and Int("hello") gives nil.

Swift Parsing with Int, Double and radix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The rules are strict and worth remembering: the whole string must be a valid number. A sign is allowed, but a leading space (" 7"), a decimal point for an Int, an underscore, or a value that does not fit into Int all give nil. Double accepts decimals, a leading dot and exponents like 1e3. With the radix: label you can parse other bases.

Because the result is optional, you must decide what happens when parsing fails. The two usual tools are if let / guard let (do something else) and ?? (use a default):

Swift Handling a failed parse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The helper readInt() combines both steps and returns nil for either problem: no more input, or text that is not an integer. This is a small example of the function style we use for tidy input code. Functions explains the syntax in detail.

Cleaning the text first

Real input has stray spaces. Remove them before parsing. trimmingCharacters(in:) comes from Foundation (add import Foundation):

Swift Trimming whitespace before parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The raw line " 12 " fails to parse; the trimmed "12" succeeds. debugDescription shows the quotes, which makes invisible whitespace visible, a trick worth keeping for debugging input problems.

Several values on one line

A common input format puts several numbers on one line, separated by spaces. Split the line, then convert each piece. compactMap converts and drops the pieces that fail; Swift's map-family functions are covered in map, filter, reduce and Friends, but the idea is simple enough to use now.

Swift Numbers on one line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

split(separator: " ") produces substrings and, by default, skips empty ones, so double spaces do no harm. compactMap { Int($0) } turns the pieces into integers and silently drops "abc", and comparing counts is how you notice that something was dropped. Whether to ignore bad values or to report them is a design decision; a calculator should report, a quick statistics script may ignore.

Reading until the input ends

For input of unknown length, loop while readLine() returns something. The pattern while let line = readLine() reads, unwraps and tests in one step:

Swift Reading all lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The loop ends when readLine() returns nil, so it reads all five lines, including the blank one. continue jumps to the next line after reporting a problem, and guard ... else handles the "wrong shape" cases in one place (guard and Early Exit and Loops go deeper). The error messages go to the same output as the normal ones here, but see below for how to send diagnostics somewhere else.

A validation loop

Interactive programs often ask again until the answer is acceptable. Here is a menu with scripted input that includes two bad answers before a good one:

Swift Ask until the answer is valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The function returns nil only when the input ends, which stops it from looping forever on a closed input. That is a common bug in beginner programs: while true plus readLine()! spins or crashes when the input is a file. The range.contains(value) test reads naturally, and ClosedRange is explained in Ranges.

Output: print, separators and standard error

You have used print since the first lesson. A few options matter for programs that interact with others:

Swift print options and standard error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

print joins its arguments with a space (or the separator) and ends with a newline (or the terminator). print(_:to:) writes into any value that conforms to TextOutputStream, and a String does, which is handy for building text without a file. Real programs separate standard output (the results, which another program might read) from standard error (messages for humans). In a C-style program you would write fputs(..., stderr), but under Swift 6's strict concurrency checking stderr is a global mutable variable and the compiler rejects it with error: reference to var 'stderr' is not concurrency-safe because it involves shared mutable state. FileHandle.standardError from Foundation is the safe replacement. In our runner both streams appear together in the output.

Pitfalls and good practice

  • Never trust readLine()! outside scripts with known input; use guard let or ?? "".
  • Parsing is strict. Trim the text first, and report what was rejected.
  • Distinguish "no more input" from "bad input". nil from readLine() and nil from Int(...) mean different things, so handle them separately when it matters.
  • Do not read input at the top of a function that is also used in tests; pass the text in as a parameter and keep the reading in a thin layer.
  • Locale: Double("3.5") expects a dot as the decimal separator regardless of the user's region; for locale-aware parsing use a NumberFormatter with the user's locale.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does readLine() return when the input has no more lines?

    readLine() returns String? and gives nil at the end of the input. An empty line gives an empty string, which is different.
  2. 2. What is Int(" 7") (a space before the digit)?

    Int(_:) requires the entire string to be a valid number, so a leading space makes the conversion fail and return nil. Trim the text first.
  3. 3. What is wrong with let n = Int(readLine()!)! for reading a number?

    Both force unwraps trap on nil, so a missing line or text like 'abc' stops the program.
  4. 4. What does while let line = readLine() { ... } do?

    The condition succeeds while readLine() returns a value and fails at nil, so the loop reads every remaining line, including empty ones.
  5. 5. Why does fputs("msg", stderr) fail to compile in Swift 6 mode?

    In Swift 6 language mode, reading a global mutable variable from C is a data-race diagnostic; use FileHandle.standardError instead.

Summary

  • readLine() returns the next line without its newline as String?, and nil at the end of the input.
  • Text becomes numbers through failable initializers: Int(_:), Double(_:), Int(_:radix:). The whole string must be valid, so trim first.
  • Handle nil with if let, guard let or ??; reserve ! for throw-away scripts.
  • split(separator:) with compactMap reads several values per line; while let line = readLine() reads until the input ends.
  • A validation loop should return nil when the input ends so it cannot spin forever.
  • print has separator, terminator and to:; use FileHandle.standardError for diagnostics in Swift 6.

Next: Operators