Apple’s docs for CustomStringConvertible
say:
Accessing a type’s
description
property directly […] is discouraged.
Why?
Below is an example where using description
seems useful to me. How would I get the same results otherwise?
func dontPrintNil(_ s: String?) {
if s == nil {
print("placeholder")
} else {
print(s!)
}
}
let s: String? = nil
dontPrintNil(s) // → placeholder
dontPrintNil(s?.description) // → placeholder
dontPrintNil(String(describing: s)) // → nil
dontPrintNil("\(s)") // → nil
String(instance)
will work for aninstance
of any type, returning itsdescription
if theinstance
happens to beCustomStringConvertible
. UsingCustomStringConvertible
as a generic constraint, or accessing a conforming type'sdescription
directly, is therefore discouraged.” (Emphasis mine.) I can’t see how the first sentence implies the second one. Do the docs assume that we always want the conversion to String to be successful?