Maury Markowitz
Maury Markowitz

Reputation: 9279

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.

Upvotes: 2

Views: 174

Answers (1)

Bradley Mackey
Bradley Mackey

Reputation: 7668

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.

Upvotes: 3

Related Questions