protocol
CustomStringConvertible
Inheritance | View Protocol Hierarchy → |
---|---|
Import |
|
Instance Variables
A textual representation of this instance.
Instead of accessing this property directly, convert an instance of any
type to a string by using the String(describing:)
initializer. For
example:
struct
Point
:
CustomStringConvertible
{
let
x
:
Int
,
y
:
Int
var
description
:
String
{
return
"(\(
x
), \(
y
))"
}
}
let
p
=
Point
(
x
:
21
,
y
:
30
)
let
s
=
String
(
describing
:
p
)
(
s
)
// Prints "(21, 30)"
The conversion of p
to a string in the assignment to s
uses the
Point
type's description
property.
Declaration
var
description
:
String
{
get
}
A type with a customized textual representation.
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.Conforming to the CustomStringConvertible Protocol
Add
CustomStringConvertible
conformance to your custom types by defining adescription
property.For example, this custom
Point
struct uses the default representation supplied by the standard library:After implementing the
description
property and declaringCustomStringConvertible
conformance, thePoint
type provides its own custom representation.See Also:
String.init<T>(T)
,CustomDebugStringConvertible