protocol CustomDebugStringConvertible
Inheritance | View Protocol Hierarchy → |
---|---|
Import | import Swift |
Instance Variables
A textual representation of this instance, suitable for debugging.
Calling this property directly is discouraged. Instead, convert an
instance of any type to a string by using the String(reflecting:)
initializer. This initializer works with any type, and uses the custom
debugDescription
property for types that conform to
CustomDebugStringConvertible
:
struct Point: CustomDebugStringConvertible {
let x: Int, y: Int
var debugDescription: String {
return "(\(x), \(y))"
}
}
let p = Point(x: 21, y: 30)
let s = String(reflecting: p)
print(s)
// Prints "(21, 30)"
The conversion of p
to a string in the assignment to s
uses the
Point
type's debugDescription
property.
Declaration
var debugDescription: String { get }
A type with a customized textual representation suitable for debugging purposes.
Swift provides a default debugging textual representation for any type. That default representation is used by the
String(reflecting:)
initializer and thedebugPrint(_:)
function for types that don't provide their own. To customize that representation, make your type conform to theCustomDebugStringConvertible
protocol.Because the
String(reflecting:)
initializer works for instances of any type, returning an instance'sdebugDescription
if the value passed conforms toCustomDebugStringConvertible
, accessing a type'sdebugDescription
property directly or usingCustomDebugStringConvertible
as a generic constraint is discouraged.Note: Calling the
dump(_:_:_:_:)
function and printing in the debugger uses bothString(reflecting:)
andMirror(reflecting:)
to collect information about an instance. If you implementCustomDebugStringConvertible
conformance for your custom type, you may want to consider providing a custom mirror by implementingCustomReflectable
conformance, as well.Conforming to the CustomDebugStringConvertible Protocol
Add
CustomDebugStringConvertible
conformance to your custom types by defining adebugDescription
property.For example, this custom
Point
struct uses the default representation supplied by the standard library:After adding
CustomDebugStringConvertible
conformance by implementing thedebugDescription
property,Point
provides its own custom debugging representation.