Why is accessing CustomStringConvertible’s description discouraged?

351 Views Asked by At

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
1

There are 1 best solutions below

0
On

As a hint, a previous version of that same piece of documentation reads:

Note: String(instance) will work for an instance of any type, returning its description if the instance happens to be CustomStringConvertible. Using CustomStringConvertible as a generic constraint, or accessing a conforming type's description directly, is therefore discouraged.

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 convenient String(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.