A type with a customized textual representation suitable for debugging purposes.
SDK
- Xcode 7.0+
Framework
- Swift Standard Library
Declaration
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 debug
function for types that don’t provide their own. To customize that representation, make your type conform to the Custom
protocol.
Because the String(reflecting:)
initializer works for instances of any type, returning an instance’s debug
if the value passed conforms to Custom
, accessing a type’s debug
property directly or using Custom
as a generic constraint is discouraged.
Note
Calling the dump(_:
function and printing in the debugger uses both String(reflecting:)
and Mirror(reflecting:)
to collect information about an instance. If you implement Custom
conformance for your custom type, you may want to consider providing a custom mirror by implementing Custom
conformance, as well.
Conforming to the CustomDebugStringConvertible Protocol
Add Custom
conformance to your custom types by defining a debug
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 "p: Point = {
// x = 21
// y = 30
// }"
After adding Custom
conformance by implementing the debug
property, Point
provides its own custom debugging representation.
extension Point: CustomDebugStringConvertible {
var debugDescription: String {
return "Point(x: \(x), y: \(y))"
}
}
print(String(reflecting: p))
// Prints "Point(x: 21, y: 30)"