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
    I read the following on [SwiftDoc.org](http://swiftdoc.org/v3indexing/protocol/CustomStringConvertible/): “`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? – Philippe-André Lorin Jan 19 '17 at 21:55

1 Answers1

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.

Cykelero
  • 199
  • 1
  • 9