6

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
  • 1
    I read the following on SwiftDoc.org: “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.” (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? Jan 19, 2017 at 21:55

1 Answer 1

1

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.