Maury Markowitz Maury Markowitz - 1 year ago 81
Swift Question

Is there a protocol associated with Swift's .description?

Since Swift 2 (3?) the "right way" to get a textual output from any old object is to use

.description
. I'd like to use
.description
in a generic function:

func checkNumeric<T>(_ value: T) -> Bool {
let nf = NumberFormatter()
nf.numberStyle = .decimal
return (nf.number(from:value.description) != nil)
}


But that doesn't work, because T doesn't support
.description
(which, IMHO, is a Very Bad Thing). In any event, is there a way to do this? There is
CustomStringConvertible
, but no
StringConvertible
, and I can't seem to find anything else similar.

Yes, I'm aware I can make my own protocol and add the classes to it with extensions. However, the whole point of this function is to avoid having to know and list every possible class that might go into the function.

Answer Source

Just assert that T must be any CustomStringConvertible, which will expose the .description property on T.

func checkNumeric<T>(_ value: T) -> Bool 
where T: CustomStringConvertible {
    let nf = NumberFormatter()
    nf.numberStyle = .decimal
    return (nf.number(from:value.description) != nil)
}

If you are creating your own classes with a description property, just make sure they conform to CustomStringConvertible. Then there's no need to create your own protocol and extend every class that may or may not be used.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download