init(reflecting:)
Creates a string with a detailed representation of the given value, suitable for debugging.
Declaration
init<Subject>(reflecting subject: Subject)Discussion
Use this initializer to convert an instance of any type to its custom debugging representation. The initializer creates the string representation of instance in one of the following ways, depending on its protocol conformance:
If
subjectconforms to theCustomDebugStringConvertibleprotocol, the result issubject.debugDescription.If
subjectconforms to theCustomStringConvertibleprotocol, the result issubject.description.If
subjectconforms to theTextOutputStreamableprotocol, the result is obtained by callingsubject.write(to: s)on an empty strings.An unspecified result is supplied automatically by the Swift standard library.
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 CustomDebugStringConvertible conformance by implementing the debugDescription 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)"