init(describing:)
Creates a string representing the given value.
init<Subject>(describing instance: Subject) where Subject : CustomStringConvertible Use this initializer to convert an instance of any type to its preferred representation as a String instance. The initializer creates the string representation of instance in one of the following ways, depending on its protocol conformance:
If
instanceconforms to theTextOutputStreamableprotocol, the result is obtained by callinginstance.write(to: s)on an empty strings.If
instanceconforms to theCustomStringConvertibleprotocol, the result isinstance.description.If
instanceconforms to theCustomDebugStringConvertibleprotocol, the result isinstance.debugDescription.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(describing: p))
// Prints "Point(x: 21, y: 30)"After adding CustomStringConvertible conformance by implementing the description property, Point provides its own custom representation.
extension Point: CustomStringConvertible {
var description: String {
return "(\(x), \(y))"
}
}
print(String(describing: p))
// Prints "(21, 30)"