Why do collections use the debugDescription on their elements?


(Martin R) #1

I wonder why the description method of collections use the debugDescription method to print their elements, and not the description method. Example:

    let s = "a\"b"
    print(s) // a"b
    print(s.debugDescription) // "a\"b"

    let x = 1.1
    print(x) // 1.1
    print(x.debugDescription) // 1.1000000000000001

    let d = [ s : x ]
    print(d) // ["a\"b": 1.1000000000000001]

- The embedded quotation mark is printed as " in print(s), but as \" in print(d).
- The floating point number is printed with a higher precision in the dictionary description.

The same happens with `Array`, `Set` and also `Optional`. Is there a special reason? It seems unnecessary and a possible cause for confusion to me.

Regards,
Martin


(Ole Begemann) #2

I wonder why the description method of collections use the debugDescription method to print their elements, and not the description method.

Dmitri Gribenko gave this reason in December 2015 [1]:

Array's description shouldn't be presented to the user in raw form,
ever, so the use case here is debugging. Thus, it makes sense to
present the debug representation of the elements in both cases.
Consider an array of strings:

var myArray = [ "", "", "" ]

If we used the regular description, then String(myArray) would be
"[ , , ]", which looks like a library bug.

[1]: https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151207/000272.html