Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 146 ยท Structures, Classes and Enums

CustomStringConvertible and Debug Output

Control how your Swift types print with CustomStringConvertible and CustomDebugStringConvertible, and inspect values with print, debugPrint, dump, String(reflecting:) and Mirror.

Printing a value is the oldest debugging tool there is. Swift gives you several levels of it, and the output depends on how the type describes itself. A plain struct prints its type name and its properties, an Int prints its digits, and a class instance prints its type name (but not its address, unlike many languages). When the default output is not helpful, two small protocols let you take control: CustomStringConvertible for text meant for people, and CustomDebugStringConvertible for text meant for developers.

This lesson covers both protocols, shows the differences between print, debugPrint and dump, and then looks under the hood with Mirror, the reflection API that powers dump. Together they make your logs and error messages far easier to read.

The default output

Before customizing anything, see what Swift gives you for free.

Swift Default printing

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.

A struct prints as Point(x: 1, y: 2), an enum case by its name, and a class as binary.Node: the module name followed by the type. Here the module is called binary, the name of the compiled program on our server; in your own project it is the module or target name. Collections and optionals print their elements with the same rule, so you see [binary.Point(x: 0, y: 0)] in an array and Optional(binary.Point(x: 5, y: 5)). A struct at the top level prints without the prefix, but the prefix appears for it inside collections. The module prefix is useful when two modules define the same type name, but noisy otherwise.

CustomStringConvertible

Conform to CustomStringConvertible and implement one property, description. Anything that turns a value into text (print, string interpolation, String(describing:)) will use it.

Swift A friendly description

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.

All four lines use the same description: 19.05 EUR, then a sentence containing 19.05 EUR and 2.50 EUR, then the array [19.05 EUR, 2.50 EUR], then 2.50 EUR. A description should be short, stable and written for a reader. Use it for text a user might see: a time, a price, a name.

Writing "\(value)" or print(value) does not look for a method called toString; Swift checks whether the type conforms to CustomStringConvertible. If you forget the conformance and only declare a description property, the property exists but print will not use it. The protocol conformance is what matters.

Forgetting the conformance

Swift description without the protocol

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 line prints Badge(name: "gold"), because Badge does not conform to CustomStringConvertible. Only the second line, which calls the property by name, shows Badge <gold>. Add : CustomStringConvertible to fix it.

Enums: a good place for descriptions

Enums often want a different public name than their case. A description with a switch keeps it exhaustive, so the compiler reminds you when you add a case.

Swift Describing an enum

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 output is Tue, then [Mon, Tue, Wed], then 3. The rawValue is unaffected by the description.

CustomDebugStringConvertible

A description for humans may hide details a developer needs. CustomDebugStringConvertible adds debugDescription, which shows the full, unambiguous state. It is used by debugPrint, by String(reflecting:), and by the debugger's po command (when you run in Xcode or lldb).

Swift description vs debugDescription

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(user) shows just the name. debugPrint(user) and String(reflecting:) show the id, the name in quotes with the inner quotes escaped, and the token length instead of the token itself. This is a good habit: a debug description is allowed to be detailed, but it should never leak secrets into logs.

One surprising point: an array prints its elements using their debugDescription, not description. So the last line shows the debug text inside brackets. Strings show it most clearly: print("hi") prints hi, while print(["hi"]) prints ["hi"], with quotes, because the elements use their debug form.

If you only implement description, debugPrint falls back to the same text for types that conform to CustomStringConvertible. If you only implement debugDescription, print uses the default output. Implement both when the two audiences differ; otherwise implement description alone.

print accepts several items, with a separator and a terminator, and can write to any TextOutputStream.

Swift Separators, terminators and streams

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 print a b c and a-b-c. The third and fourth join into no newline ... then continue. Collector receives every piece of output print writes, including newlines, so after two prints it holds first\nsecond\n, which is 13 characters. Writing to a TextOutputStream is a clean way to test code that prints, or to send output to a file or a log.

dump: the full tree

print is for a line. dump prints the whole structure of a value, with nested properties indented and types shown. It works for any value, without any protocol conformance, because it uses reflection.

Swift dump a nested value

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 line is the type (โ–ฟ binary.Person). โ–ฟ marks a value with children, - a leaf, and names such as address and city come from the property labels. With maxDepth: 1 the nested Address and the array are collapsed to โ–น address: binary.Address and โ–น nicknames: 2 elements, which is handy for big structures. dump ignores CustomStringConvertible for the structure but uses descriptions of leaf values where available.

Mirror: reflection

dump is built on Mirror. A mirror lets you inspect a value's stored properties at runtime: their labels, their values and the structure around them. You create one with Mirror(reflecting: value) and walk its children.

Swift Listing properties with Mirror

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.

For Config you see the three properties in declaration order: host = localhost, port = 8080, debug = true. The displayStyle is Optional(Swift.Mirror.DisplayStyle.struct) and there are 3 children. A tuple's children are labeled .0 and .1, and the array's elements have no label, which our helper prints as ?.

Mirror is read-only and fairly slow, so use it for debugging helpers, logging, tests and tools, not in tight loops. It does not see computed properties, and private stored properties of types in other modules may be hidden. For production serialization use Codable instead.

Customizing a mirror

A type can control what Mirror and dump reveal by conforming to CustomReflectable. This is useful for hiding secrets or presenting a computed view.

Swift CustomReflectable hides a secret

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.

dump now shows the password as dots, because it asks the custom mirror instead of reading the stored property. The dictionary literal gives the labels; since Swift dictionaries have no stable order, in real code you might prefer an array of (label, value) pairs when order matters.

Printing in tests and logs: a checklist

  • User-facing text: write a deliberate description, or better, a dedicated method such as formatted(); descriptions are for diagnostics and simple cases.
  • Developer-facing text: put detail in debugDescription, and keep secrets out.
  • Never parse a description. Its format is not a contract. Use Codable for data exchange.
  • Beware recursion: in description, writing "\(self)" calls description again and loops forever. Interpolate individual properties instead.
  • Avoid heavy work in descriptions. They run implicitly whenever a value is printed or logged.

A classic mistake: infinite recursion

Swift description that calls itself (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.

Interpolating self inside description asks Swift for the description of self, which asks for the description of self, and so on until the stack is exhausted and the process is killed. The program prints start, then the runner stops it (here with SIGKILL) and shows no result for the second print. Fix it by interpolating a stored property instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do you implement to control the text that print(value) and string interpolation produce?

    print and interpolation use description for types that conform to CustomStringConvertible. A property named description alone is not enough.
  2. 2. Which function uses debugDescription?

    debugPrint and String(reflecting:) use CustomDebugStringConvertible, while print and String(describing:) use description.
  3. 3. What does dump(value) show that print(value) usually does not?

    dump uses reflection to print the whole structure, indented, with property labels.
  4. 4. Why is var description: String { "X(\(self))" } a bug?

    Interpolating self asks for self's description, which is the property being computed, so the recursion never ends.
  5. 5. What is Mirror best suited for?

    Mirror is read-only reflection. It is slow and not a replacement for Codable or protocols.

Summary

  • Default printing shows a struct's properties, an enum case's name and a class's type name.
  • CustomStringConvertible.description controls print, interpolation and String(describing:); the protocol conformance is required.
  • CustomDebugStringConvertible.debugDescription controls debugPrint, String(reflecting:) and elements printed inside collections; keep secrets out of it.
  • print supports separator, terminator and to: any TextOutputStream.
  • dump prints a whole value tree via reflection; Mirror(reflecting:) exposes children programmatically; CustomReflectable customizes what they see.
  • Do not interpolate self in description, and never parse description output.

Next: Protocols