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
As a hint, a previous version of that same piece of documentation reads:
To me, this suggests that what they're worried about, is people needlessly going out of their way to cast values to
CustomStringConvertible
, instead of using the more convenientString(describing:)
.If you don't know about that initializer, casting (or using generic constraints) would indeed be the natural thing to reach for.
Now—why did they eventually remove the “therefore” logical link from the comment? Maybe it's just a side-effect of the rewrite, or maybe they feel it's not that simple, which would mean we still don't have our answer.