A type with a customized textual representation.
protocol CustomStringConvertible
Types that conform to the
CustomStringConvertible
protocol can provide their own representation to be used when converting an instance to a string. TheString(describing:)
initializer is the preferred way to convert an instance of any type to a string. If the passed instance conforms toCustomStringConvertible
, theString(describing:)
initializer and theprint(_:)
function use the instance’s customdescription
property.Accessing a type’s
description
property directly or usingCustomStringConvertible
as a generic constraint is discouraged.
description
속성에 직접 액세스하거나 제네릭 제약 조건으로 사용하는 것은 권장되지 않음Add CustomStringConvertible
conformance to your custom types by defining a description
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(p)
// Prints "Point(x: 21, y: 30)"
After implementing the description
property and declaring CustomStringConvertible
conformance, the Point
type provides its own custom representation.
extension Point: CustomStringConvertible {
var description: String {
return "(\\(x), \\(y))"
}
}
print(p)
// Prints "(21, 30)"