我有一个协议,定义如下:
protocol MyProtocol {
...
}
我也有一个通用的结构体:
struct MyStruct <T> {
...
}
最后我有了一个通用函数:
func myFunc <T> (s: MyStruct<T>) -> T? {
...
}
我希望在函数内部测试类型 T 是否符合 MyProtocol。实际上,我想能够执行以下伪代码:
let conforms = T.self is MyProtocol
但是这会抛出编译错误:
error: cannot downcast from 'T.Type' to non-@objc protocol type 'MyProtocol'
let conforms = T.self is MyProtocol
~~~~~~ ^ ~~~~~~~~~~
我也尝试过一些变化,例如 T.self is MyProtocol.self
、T is MyProtocol
,以及使用 ==
替换 is
。但是目前还没有取得任何进展。有什么想法吗?