【问题标题】:How do I check the class of an instance that conforms to a protocol in swift?如何快速检查符合协议的实例的类?
【发布时间】:2018-07-04 08:27:24
【问题描述】:

我正在尝试检查符合协议的实例的类。

我有一个协议。

protocol ToolbarProtocol {

  func show()

  func hide()

}

我有一个符合该协议的类。

class GameToolbar: ToolbarProtocol {
...
}

我创建了一个管理器类来管理我的工具栏。

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

在这个管理器中,我有一个函数要查找特定类型工具栏的第一个实例。

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

我不能在toolbar 上调用isKind(of),以前当我的工具栏是由外部库提供的另一种类时(我试图从我的代码库中删除它,因为我想要不同的功能) .

我尝试让我的协议扩展 AnyObject,但我认为这无论如何都是隐含的,并且没有效果。

如何检查符合给定协议的实例数组,以检查特定的类类型?

【问题讨论】:

    标签: swift swift4 swift-protocols


    【解决方案1】:

    我认为您需要尝试投射它,例如

    if let vc = toolbar as? GameToolbar {}
    

    在你的情况下,你可能需要这样的东西:

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

    【讨论】:

    • 好答案。只这样做就足够了:return existingToolbars[.east]?.first as?游戏工具栏
    • 谢谢,先as? GameToolbar 只会检查列表中的第一个,不是吗? first where { condition } 会给你第一个匹配条件的地方,所以会检查每个元素,直到找到匹配或失败
    • 是的,你是对的。我首先假设了另一个功能。
    • 在尝试构建该解决方案时,建议的修复方法是简单地执行 toolbar is GameToolbar
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多