ProtocolSwift

CustomDebugStringConvertible

A type with a customized textual representation suitable for debugging purposes.

protocol CustomDebugStringConvertible

Overview

Swift provides a default debugging textual representation for any type. That default representation is used by the String(reflecting:) initializer and the debugPrint(_:) function for types that don’t provide their own. To customize that representation, make your type conform to the CustomDebugStringConvertible protocol.

Because the String(reflecting:) initializer works for instances of any type, returning an instance’s debugDescription if the value passed conforms to CustomDebugStringConvertible, accessing a type’s debugDescription property directly or using CustomDebugStringConvertible as a generic constraint is discouraged.

Conforming to the CustomDebugStringConvertible Protocol

Add CustomDebugStringConvertible conformance to your custom types by defining a debugDescription property.

For example, this custom Point struct uses the default representation supplied by the standard library:

struct Point {
    let x: Int, y: Int
}

let p = Point(x: 21, y: 30)
print(String(reflecting: p))
// Prints "Point(x: 21, y: 30)"

After adding CustomDebugStringConvertible conformance by implementing the debugDescription property, Point provides its own custom debugging representation.

extension Point: CustomDebugStringConvertible {
    var debugDescription: String {
        return "(\(x), \(y))"
    }
}

print(String(reflecting: p))
// Prints "(21, 30)"

Refinements

Requirements

Instance Properties

Conforming Types