Swift: check if generic type conforms to protocol

Alex picture Alex · Jan 24, 2015 · Viewed 71.5k times · Source

I have a protocol that I defined like so:

protocol MyProtocol {
   ...
}

I also have a generic struct:

struct MyStruct <T>  {
    ...
}

Finally I have a generic function:

func myFunc <T> (s: MyStruct<T>) -> T? {
   ...
}

I'd like to test inside of the function if the type T conforms to MyProtocol. Essentially I'd like to be able to do (~ pseudocode):

let conforms = T.self is MyProtocol

But this throws a compiler error:

error: cannot downcast from 'T.Type' to non-@objc protocol type 'MyProtocol'
   let conforms = T.self is MyProtocol
                  ~~~~~~ ^  ~~~~~~~~~~

I have also tried variations, like T.self is MyProtocol.self, T is MyProtocol, and using == instead of is. So far I haven't gotten anywhere. Any ideas?

Answer

maquannene picture maquannene · Jul 5, 2016

I have to say @Alex want to check if T type conforms to protocol rather than s. And some answerer didn't see clearly.

Check T type conforms to protocol like this :

if let _ = T.self as? MyProtocol.Type {
    //  T conform MyProtocol
}

or

if T.self is MyProtocol.Type {
    //  T conform MyProtocol
}