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

David Sweeris davesweeris at mac.com
Thu Oct 5 11:18:36 CDT 2017


That was my point... `foo` doesn’t have a `T: Numeric` version, therefore when it calls `isNumeric` the compiler has to call the version that always return false. `bar` is overloaded with both a `T` and a `T: Numeric` version, so there the compiler can call the most appropriate version of `isNumeric`.

- Dave Sweeris

> On Oct 5, 2017, at 01:49, Alex Blewitt <alblue at apple.com> wrote:
> 
> I think one of your 'foo' or 'bar' is missing a <T:Numeric>, as otherwise the functions are identical ...
> 
> Alex
> 
>> On 5 Oct 2017, at 09:23, David Sweeris via swift-users <swift-users at swift.org> wrote:
>> 
>> 
>> 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
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171005/b5abdb61/attachment.html>


More information about the swift-users mailing list