简体   繁体   English

如何快速检查符合协议的实例的类?

[英]How do I check the class of an instance that conforms to a protocol in swift?

I'm trying to check the class of an instance which conforms to a protocol. 我正在尝试检查符合协议的实例的类。

I have a protocol. 我有一个协议。

protocol ToolbarProtocol {

  func show()

  func hide()

}

I have a class which conforms to that protocol. 我有一个符合该协议的类。

class GameToolbar: ToolbarProtocol {
...
}

I have a manager class I createed to manage my toolbars. 我创建了一个管理器类来管理工具栏。

class ToolbarManager {
  var existingToolbars: [Game.rotation: Array<ToolbarProtocol>]
}

In this manager, I have a function that wants to find the first instance of a specific type of toolbar. 在此管理器中,我有一个函数想要查找特定类型的工具栏的第一个实例。

func getDebugToolbar() -> ToolbarProtocol? {
    return existingToolbars[.east]?.first(where: { (toolbar: ToolbarProtocol) -> Bool in
      toolbar.isKind(of: GameToolbar.self) //This line causes an error because .isKind is not a member of ToolbarProtocol
    })
  }

I can't call isKind(of) on toolbar , which previously worked when my toolbars were a different kind of class provided by an external library (which I'm trying to remove from my codebase because I want different functionality). 我无法在toolbar上调用isKind(of) ,该toolbar以前可以在我的工具栏是由外部库提供的另一种类时使用(我想从我的代码库中删除该类,因为我想要其他功能)。

I tried making my protocol extend AnyObject , but I think that's implicit anyway, and it had no effect. 我试图使我的协议扩展AnyObject ,但是我认为这是隐式的,并且没有任何效果。

How can I check an array of instances which conform to a given protocl, to check for specific class types? 如何检查符合给定协议的实例数组,以检查特定的类类型?

I think you would need to attempt to cast it, like 我认为您需要尝试投射它,例如

if let vc = toolbar as? GameToolbar {}

In your case, you might need something like this: 在您的情况下,您可能需要以下内容:

func getDebugToolbar() -> ToolbarProtocol? {
    return existingToolbars[.east]?.first(where: { (toolbar: ToolbarProtocol) -> Bool in
      let _ = toolbar as? GameToolbar
    })
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM