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?
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
}