I have the following:
extension Data : CustomStringConvertible {
var description : String {
return base64EncodedString()
}
}
This shows a warning:
Conformance of 'Data' to protocol 'CustomStringConvertible' was already stated in the type's module 'Foundation'
And because of this warning, Data
isn’t printed using the description
.
Is this not supported?
2
Answers
As the error says,
Data
already conforms toCustomStringConvertible
(andCustomDebugStringConvertible
) and thus already have adescription
property.You cannot override this property (nor can you inherit from Data, as it’s a struct)
Instead you need to (and should) create a different property for your custom description.
For example:
However it’s somewhat pointless, as you might as well just call the method directly, unless there’s more to your code.
As Claus Jørgensen’s answer says, you cannot "override" the protocol witness
description
in your own extension.If the whole purpose of doing this is just so you can directly
print
the data, there is an alternative.You see,
print
doesn’t just useCustomStringConvertible.description
to print values.print
just usesString.init(describing:)
to work out what string to print, andString.init(describing:)
would first check if the value conforms toTextOutputStreamable
, before it checks forCustomStringConvertible
conformance.Luckily,
Data
doesn’t conform toTextOutputStreamable
, so you can writeThat said, this would be a problem when in some future version
Data
does conform toTextOutputStreamable
. Therefore, the best thing to do is to bite the bullet and explicitly writedata.base64EncodedString()
in yourprint
calls.