本文介绍了Swift:检查泛型类型是否符合协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我定义的协议:

$ p $协议MyProtocol {
...
}

我也有一个通用结构:

  struct MyStruct< T> {
...
}

最后我有一个通用函数:

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

我想在里面测试如果类型T符合MyProtocol,则为函数。基本上我希望能够做到(〜伪代码):

  let conforms = T.self是MyProtocol 

但是这会引发编译器错误:

 错误:无法从'T.Type'下降到非@ objc协议类型'MyProtocol'
let conforms = T.self是MyProtocol
~~~~~~ ^ ~~~~~~~~~~

我也尝试过变体,例如 T.self是MyProtocol.self T是MyProtocol ,并使用 == 而不是。到目前为止,我没有得到任何地方。任何想法?

解决方案

有点迟了,但您可以测试某些事情是否对作为响应 test:

 如果让currentVC = myViewController为? MyCustomProtocol {
// currentVC响应MyCustomProtocol协议=]
}

编辑:稍微短一点:

  if let _ = self as? MyProtocol {
// match
}

使用一个警卫

  guard let _ = self as? MyProtocol else {
//不匹配
返回
}


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?

解决方案

A bit late but you can test if something responds to protocol with as ? test:

if let currentVC = myViewController as? MyCustomProtocol {
    //currentVC responds to the MyCustomProtocol protocol =]
}

EDIT: a bit shorter:

if let _=self as? MyProtocol {
// match
}

And using a guard

guard let _=self as? MyProtocol else {
    // doesn't match
    return
}

这篇关于Swift:检查泛型类型是否符合协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:03