我有一个我定义的协议:
protocol MyProtocol {
...
}
Run Code Online (Sandbox Code Playgroud)
我也有一个通用的结构:
struct MyStruct <T> {
...
}
Run Code Online (Sandbox Code Playgroud)
最后我有一个通用的功能:
func myFunc <T> (s: MyStruct<T>) -> T? {
...
}
Run Code Online (Sandbox Code Playgroud)
如果类型T符合MyProtocol,我想测试函数内部.基本上我希望能够做到(〜伪代码):
let conforms = T.self is MyProtocol
Run Code Online (Sandbox Code Playgroud)
但这会引发编译器错误:
error: cannot downcast from 'T.Type' to non-@objc protocol type 'MyProtocol'
let conforms = T.self is MyProtocol
~~~~~~ ^ ~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
我也曾尝试变化,比如T.self is MyProtocol.self,T is MyProtocol以及使用==替代is.到目前为止,我还没有到任何地方.有任何想法吗?