> On Sep 21, 2017, at 3:58 PM, V T via swift-users <swift-users@swift.org> 
> wrote:
> 
> Hi there!
> 
> Is there a best way to check if a given type conforms to numeric protocol 
> (Integer or FP) at runtime?
> 
> func checkNumeric<T>(_ value: T) {
>       /* return true if vaiue is Integer or FP */
>       /* this will not compile: */
>       if value is Numeric {
>               
>       }
> }
> 
> Best regards!
> 
> VT
> 

I think the way to do it is to try casting as the type, but you can't use "as? 
Numeric" as you get:

 error: protocol 'Numeric' can only be used as a generic constraint because it 
has Self or associated type requirements

but you could check for each specific numeric type such as:

func checkNumeric<T>(_ value: T) {
    if (value as? Int != nil) || (value as? Float != nil) {
        print("numeric")
    } else {
        print("not numeric")
    }
}

checkNumeric(3)
checkNumeric(3.0)
checkNumeric("3")

HTH,
Dave


_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to