"Accessing a type's `description` property directly ... is discouraged" - Why?

The documentation for CustomStringConvertible says:

Accessing a type's description property directly or using
CustomStringConvertible as a generic constraint is discouraged.

But this is never elaborated upon. Why is it discouraged to write aThing.description?

Since this is also a requirement of LosslessStringConvertible, it seems more straightforward to me that aThing.description matches with ThingType.init?(_ description: String) (i.e. I got a string directly from the object, so I expect the object also knows how to parse that String).

Using String(describing: aThing) seems too indirect for my liking. Is String doing anything other than returning the description? I don't know. Neither does the object who expects to parse this string again.

1 Like

I don't have an official answer, but I wrote about my interpretation of this guidance a few years ago: Why you’re not supposed to call description

The reason for this rule is that every value in Swift is convertible to a string , regardless of a type’s conformance to one or both of these protocols. The protocols only exist to allow customization of a type’s textual representation. In particular, don’t ever use these protocols as types or generic constraints.

I understand that, but it seems like, for LosslessStringConvertible types in particular (see edited post above), that it's doing more than just customising its textual representation; it's actually serialising the data in a specific format and expects exactly that format back.

EDIT: Ok, you do mention that in your post.

When you rely on LosslessStringConvertible semantics, you should absolutely access the description property directly, despite the above advice to the contrary.

So I agree with you there.

Terms of Service

Privacy Policy

Cookie Policy