简体   繁体   中英

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).

I tried making my protocol extend AnyObject , but I think that's implicit anyway, and it had no effect.

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
    })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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