Debug Print

suggest change

Debug Print shows the instance representation that is most suitable for debugging.

print("Hello")
debugPrint("Hello")

let dict = ["foo": 1, "bar": 2]

print(dict)
debugPrint(dict)

Yields

>>> Hello
>>> "Hello"
>>> ["foo": 1, "bar": 2]
>>> ["foo": 1, "bar": 2]

This extra information can be very important, for example:

let wordArray = ["foo", "bar", "food, bars"]

print(wordArray)
debugPrint(wordArray)

Yields

>>> ["foo", "bar", "food, bars"]
>>> ["foo", "bar", "food, bars"]

In current Swift, print on a collection already uses the debug representation of its elements, so both lines match. In early Swift versions print(wordArray) showed [foo, bar, food, bars], where the comma inside "food, bars" looks like another element, so the array appears to have 4 elements instead of 3. Prefer debugPrint when debugging.

Updating a class's debug and print values

Printable and DebugPrintable were renamed in Swift 2 to CustomStringConvertible and CustomDebugStringConvertible.

struct Foo: CustomStringConvertible, CustomDebugStringConvertible {
    var description: String { return "Clear description of the object" }
    var debugDescription: String { return "Helpful message for debugging" }
}

let foo = Foo()

print(foo)
debugPrint(foo)
Clear description of the object
Helpful message for debugging

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents