Thursday, September 6, 2018

Why You’re Not Supposed to Call Swift’s description

Ole Begemann:

However, you should absolutely not use the following pattern, where a function argument is constrained to Custom[Debug]StringConvertible, either with a generic constraint or a plain type specification[…]

[…]

Instead, the function should accept any type, because anything is printable:

func doSomething3<T>(with x: T) {
    // ...
    // Call String(describing: x)
}

[…]

When you rely on LosslessStringConvertible semantics, you should absolutely access the description property directly, despite the above advice to the contrary. As we have seen, the alternative String(describing:) prefers Text​Output​Streamable’s representation over description if it’s available, and you can’t be 100 % certain that representation is identical to the value’s description, however unlikely any differences are.

Comments RSS · Twitter

Leave a Comment