> On Oct 4, 2017, at 18:30, Kevin Lundberg via swift-users
> <swift-users@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@swift.org
https://lists.swift.org/mailman/listinfo/swift-users