Making String conform to CustomStringConvertible

I noticed that String is perhaps the only "basic" type in Swift that doesn't conform to CustomStringConvertible, why is that?


It's easy to make String conform to CustomStringConvertible, but is that discouraged and if so why?


Some code to illustrate the above:

// Uncomment this extension to make String conform and thus remove the two errors below:
//extension String: CustomStringConvertible { public var description: String { return self } }

let a: CustomStringConvertible = String("Hello").utf8 // Ok (since String.UTF8View conforms to CustomStringConvertible)
let b: CustomStringConvertible = String("Hello") // Error: 'String' is not convertible to 'CustomStringConvertible'.

let c: [CustomStringConvertible.Type] = [Int.self, StaticString.self] // Ok (since Int and StaticString conforms to CustomStringConvertible)
let d: [CustomStringConvertible.Type] = [Int.self, String.self] // Error: Type 'String' does not conform to protocol 'CustomStringConvertible'.
Accepted Answer

As the comment on CustomStringConvertible says,


/// - 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.
///
/// - SeeAlso: `String.init<T>(T)`, `CustomDebugStringConvertible`


In other words, why bother making string conform to CustomStringConvertible unless you are trying to change its representation by print(s) or String(s)? If you are using

CustomStringConvertible
other than in a conformance declaration, you're needlessly limiting the applicability of your code, since lots of types have sensible string representations without conforming to
CustomStringConvertible
(e.g. because they conform to
CustomDebugStringConvertible
or
CustomReflectable
).


Hope this helps,

Dave

Ah, that makes sense, thanks.

Making String conform to CustomStringConvertible
 
 
Q