[swift-users] Detect if a generic type is numeric

David Sweeris davesweeris at mac.com
Thu Oct 5 03:23:44 CDT 2017


> On Oct 4, 2017, at 18:30, Kevin Lundberg via swift-users <swift-users at swift.org> wrote:
> 
> Can you do something like this?
> 
> func isNumber<T: Numeric>(_ value: T) -> Bool { return true }
> 
> func isNumber<T>(_ value: T) -> Bool { return false }
> 
> I don't recall whether or not swift will pick the right version of the function here, or whether this can even compile (mac isnt open at the moment), but if you can overload functions in this way then it might be much nicer than checking for lots of concrete types.
> 

It’ll compile, but you’ll get the wrong answer if it’s called from another generic function that isn’t similarly overloaded for `T` vs `T: Numeric`. I’m not at my computer right now, but IIRC, this is correct:

func foo<T> (_ value:T) -> Bool {
    return isNumber(value)
}
func bar<T> (_ value:T) -> Bool {
    return isNumber(value)
}
func bar<T: Numeric> (_ value:T) -> Bool {
    return isNumber(value)
}
isNumber(0) //true
isNumber(“”) //false
foo(0) //false
foo(“”) //false
bar(0) //true
bar(“”) //false

- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171005/b98ef406/attachment.html>


More information about the swift-users mailing list