Skip to content
Tutorials Center
My learning

Topics

Lesson 103 of 146 ยท Standard Library and Foundation

Printing and Debugging

Learn Swift debugging output: print options, debugPrint, dump, custom descriptions, #fileID and #line, assert versus fatalError, and where os.Logger fits.

Sooner or later every program does something you did not expect, and the fastest way to find out why is often to look at it. Swift gives you a small family of tools for that: print, debugPrint, dump, the special literals #fileID, #line and #function, and the assertion functions. They look similar and they are not interchangeable. Knowing which one to reach for saves a lot of time.

This lesson covers each tool, what exactly it prints, how to control the text your own types produce, how to write a tiny logging helper that reports where a message came from, and where real logging (os.Logger) and the debugger fit in. Everything runnable here is checked on the site's Swift 6.3 toolchain on Linux.

print takes any number of values, converts each with its description, separates them with a space and ends with a newline. Two labelled arguments change that: separator and terminator. A third, to:, redirects the output to any TextOutputStream:

Swift print options and the error stream

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.

You see a b c, then a-b-c, then loading...done on one line, then the item line items: [1, 2, 3] ["k": 1] 3.0 true. The two print(..., to: &errors) lines show the point of TextOutputStream: it is a one-method protocol (write(_:)), and String itself conforms to it, so print(x, to: &someString) appends to a string instead of writing to the console. On this site, standard output and standard error are both shown in the output panel, but on a real terminal you can redirect them separately (program > out.txt 2> errors.txt), and diagnostics belong on standard error so they do not pollute the program's real output.

print writes to standard output, which is buffered when it is not a terminal. If a program crashes, the last lines you printed may never appear. The runner on this site uses line buffering, so you will see them, but in a real pipeline you may need fflush(stdout) or to write to standard error, which is unbuffered.

print shows the friendly form of a value. debugPrint shows the unambiguous form, the one you would use to tell two values apart in a log. The difference is mostly about strings, optionals and type names:

Swift print, debugPrint and what they call

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 two lines read Point(x: 1, y: 2) and binary.Point(x: 1, y: 2). The debug form adds the module name (the runner compiles your file as a module called binary; in your own project it is your target name) so you know exactly which Point it is. For strings, print gives say "hi" and debugPrint gives "say \"hi\"" with quotes and escapes, so invisible characters and stray quotes become visible. An optional keeps its wrapper in both forms (Optional("Ada")), which is why print(name as Any) is not the plain Ada you might expect. Kind.boxed(3) prints as boxed(3) and as binary.Kind.boxed(3).

The two functions map onto two protocols and two initializers:

You write It uses Protocol you can adopt
print(x), "\(x)", String(describing: x) the friendly description CustomStringConvertible (description)
debugPrint(x), String(reflecting: x) the debug description CustomDebugStringConvertible (debugDescription)

Inside collections, Swift always uses the debug form of the elements, which is why print(["a"]) shows ["a"] with quotes and not [a]. We covered the protocols in CustomStringConvertible and friends; here is the practical consequence for debugging:

Swift Choosing what your type prints

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 friendly $19.99 appears for print and interpolation. The array print, debugPrint and String(reflecting:) all show Money(cents: 1999). Give a type both: a short human form for users and an exact form for developers. If you adopt only CustomStringConvertible, Swift uses it for both purposes, which is a common source of confusion when a log hides a value's raw state. Interpolating a custom type with \(...) calls description, so never put secrets (tokens, passwords) in a description, because it ends up in logs.

dump: look inside a value

print shows what a value says about itself. dump walks the value's actual structure with a mirror, showing every stored property, nested values, enum cases and even class identity (#0, #1) so you can tell shared references apart. (A type with a custom debugDescription gets that text as its header line, as dump(price) showed above, but the stored properties are still listed underneath.)

Swift dump: the structure of values

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.

Read the output from the top. A struct shows as โ–ฟ binary.Point with its fields indented (- x: 1). A class instance gets a number: binary.Node #0. Its optional field expands to Optional(binary.Node) with a some child, and the end of the chain is - next: nil. A collection is labelled name: 2 elements. An enum with an associated value shows the case and its payload. A tuple shows .0 and .1. maxDepth: 1 stops expanding with the โ–น marker, which keeps big object graphs readable. dump(_:to:) writes into a string (3 lines here: the header and two fields), which is handy in tests.

Use dump when print hides what you need: types with a short custom description, deep structures, or classes whose identity matters. It returns its argument, so you can even wrap an expression: let total = dump(a + b).

Saying where a message came from

A bare print("here") is useless once you have twenty of them. Swift has compiler-provided literals that expand to the location of the call:

  • #fileID: the module and file, like binary/main.swift (safe to ship; no machine paths)
  • #filePath: the full path on the build machine (leaks directory names, avoid in logs)
  • #line and #column: numbers
  • #function: the enclosing function or method name, like work()

The trick is to use them as default argument values. The default is evaluated at the call site, so a helper reports where it was called from, not where it is defined:

Swift A small logging helper with call-site info

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.

Look at what happened. The .debug messages never appear because they are below the minimum. Because the message parameter is an @autoclosure (see Escaping closures and autoclosure), the string is only built when the message is actually logged: expensiveSummary() is called for each .info line (you see its (building summary) print twice) but the .debug interpolation "starting order \(order)" was never even evaluated. That matters when a message needs an expensive computation. The location comes out as binary/main.swift:LINE process(order:log:) - ..., where the line is the line of the log(...) call. #function for a function with labels shows the labels, process(order:log:).

Standard assert, precondition and fatalError use the same trick, which is why they can report the file and line of the failing call.

When your logging helper is generic enough to be useful, wrap it in a small type like Log above and pass it around, instead of a global function. In Swift 6 a global mutable level (var logLevel = Level.info) is a data-race error as soon as two tasks use it, so configuration should be a let or a value you inject.

Assertions: checks that crash on purpose

Printing is passive. An assertion states something that must be true and stops the program if it is not. Swift has four, covered in depth in Assertions and preconditions:

Function Checked in debug build Checked in optimized build (-O)
assert(cond, msg) yes no (not even evaluated)
assertionFailure(msg) yes no
precondition(cond, msg) yes yes (stops with a trap)
fatalError(msg) always always, prints the message

The server that compiles your code on this site uses an optimized build, which makes the difference visible:

Swift assert is removed in optimized builds

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.

Both lines after the assert run, and sideEffect was called never appears: in an optimized build the assertion and its condition disappear. Never put work that has to happen inside an assert. Also notice that #if DEBUG is only true if the build passes -DDEBUG; Xcode does that for Debug configurations, but swiftc does not, so here the second branch runs.

When a check must hold in production too, use precondition or fatalError. The second one is also how you mark code that should be unreachable:

Swift fatalError names what went wrong (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 call prints 100, then the program stops with this message on standard error: binary/main.swift:7: Fatal error: safe mode needs a fallback speed. The file name and line come from the same #fileID and #line defaults. A failing precondition or an out-of-range array index stops the program too, but in this optimized build you get only the crash (Illegal instruction and a backtrace) and no message text, so for crashes you want to explain, fatalError with a clear message is the better tool.

Real logging and the debugger

print is a debugging aid. It has no levels, no filtering, no timestamps and no way to turn it off in release builds. For anything that ships, apps use a logging system:

Swift
// Read-only example: Apple platforms only. os.Logger does not exist on Linux or in this sandbox.
import os

let logger = Logger(subsystem: "com.example.shop", category: "checkout")
logger.info("Order \(orderID, privacy: .public) placed")
logger.error("Payment failed: \(error.localizedDescription, privacy: .private)")

Logger is fast, filters by level, stores nothing for debug messages unless asked, and redacts dynamic values by default (they show as <private> unless marked .public), which protects user data. On servers, the Swift ecosystem uses the swift-log package (import Logging), which is a common API with pluggable back ends; that needs SwiftPM and is not available in this sandbox.

For stepping through code you use the debugger. In Xcode or on the command line with lldb, you set a breakpoint and inspect values without changing the code:

Terminal
# Read-only example: needs a real toolchain.
swiftc -g main.swift -o app    # -g keeps debug information
lldb ./app
(lldb) breakpoint set --file main.swift --line 12
(lldb) run
(lldb) frame variable          # show local variables
(lldb) po someObject           # print description (uses debugDescription)
(lldb) bt                      # backtrace

po ("print object") calls your debugDescription, so the work you put into a good debug description pays off again there. The usual workflow: reproduce with print or dump while exploring, switch to the debugger for stubborn problems, then replace temporary prints with real logging and assertions before you ship.

Habits that help

  • Print labels and context: print("count =", items.count) beats print(items.count).
  • Prefer dump over print for unfamiliar structures and for class instances.
  • Remove or convert print calls before release; use #if DEBUG for noisy diagnostics.
  • Keep logging pure: the message should never change program behaviour.
  • Don't log secrets, personal data or whole request bodies.
  • Make crashes explain themselves: fatalError("unexpected state: \(state)").

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which call shows a String with its quotes and escapes?

    debugPrint uses the debug description, so strings appear quoted and escaped. print and String(describing:) use the friendly description.
  2. 2. A type adopts only CustomStringConvertible. What does debugPrint show for it?

    If a type has no debugDescription, Swift falls back to its description for debug output as well. Add CustomDebugStringConvertible when you want a separate, more exact form.
  3. 3. Why use #fileID and #line as default parameter values in a helper?

    Default values for these literals are expanded where the call is written, not where the function is defined. That is how assert and fatalError report their caller.
  4. 4. In an optimized (-O) build, what happens to assert(expensiveCheck(), "msg")?

    assert and assertionFailure are for debug builds only. In optimized builds the condition is not even evaluated, so never rely on side effects inside it.
  5. 5. What does dump show that print usually does not?

    dump walks the value with a mirror: every stored property, enum payload, collection element, and a #n identity marker for class instances.

Summary

  • print shows the friendly description, supports separator, terminator and to: (any TextOutputStream); send diagnostics to standard error.
  • debugPrint and String(reflecting:) use debugDescription; collections always show elements in debug form.
  • Adopt CustomStringConvertible for users and CustomDebugStringConvertible for developers; never put secrets in either.
  • dump prints the real structure of a value, numbers class instances and accepts name:, maxDepth: and to:.
  • #fileID, #line and #function as default arguments report the call site; @autoclosure avoids building messages that are filtered out.
  • assert vanishes in optimized builds; use precondition or fatalError for checks that must hold in production.
  • Use os.Logger or swift-log and a debugger such as lldb for real work; both are read-only on this site.

Next: Sort Details