我有一个协议,我定义如下:
protocol MyProtocol { ... }
我也有一个通用结构:
struct MyStruct <T> { ... }
最后我有一个通用的功能:
func myFunc <T> (s: MyStruct<T>) -> T? { ... }
我想测试内部的函数,如果类型T符合MyProtocol。基本上我想要能够做(〜pseudocode):
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是MyProtocol.self,T是MyProtocol,并使用==而不是。到目前为止我还没有到任何地方。有任何想法吗?
有点晚,但你可以测试是否有一些响应协议为?测试:
if let currentVC = myViewController as? MyCustomProtocol { //currentVC responds to the MyCustomProtocol protocol =] }
编辑:有点较短:
if let _=self as? MyProtocol { // match }
和使用警卫
guard let _=self as? MyProtocol else { // doesn't match return }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。