【问题标题】:Swift @objc protocol - distinguish optional methods with similar signatureSwift @objc 协议 - 区分具有相似签名的可选方法
【发布时间】:2016-03-09 06:40:39
【问题描述】:

假设我们在 Swift 中有一个协议:

@objc protocol FancyViewDelegate {
  optional func fancyView(view: FancyView, didSelectSegmentAtIndex index: Int)
  optional func fancyView(view: FancyView, shouldHighlightSegmentAtIndex index: Int) -> Bool
}

请注意,这两种方法都是可选的,并且具有相同的前缀签名。

现在我们的FancyView 类看起来像这样:

class FancyView: UIView {
  var delegate: FancyViewDelegate?

  private func somethingHappened() {
    guard let delegateImpl = delegate?.fancyView else {
      return
    }

    let idx = doALotOfWorkToFindTheIndex()

    delegateImpl(self, idx)
  }
}

编译器在我们面前跳跃:



我们可以将somethingHappened() 更改为:

private func somethingHappened() {
  let idx = doALotOfWorkToFindTheIndex()

  delegate?.fancyView?(self, didSelectSegmentAtIndex: idx)
}

但是,正如您所见,我们冒着做大量工作的风险,只是事后丢弃了索引,因为委托没有实现可选方法。

问题是:我们如何if letguard let 绑定两个具有相似前缀签名的可选方法的实现。

【问题讨论】:

  • 如果支持,我仍然会使用 respondsToSelector 并调用相关方法。

标签: swift optional swift-protocols


【解决方案1】:

首先,您的目标 C 协议需要向 NSObjectProtocol 确认,以确保我们可以自省它是否支持给定的方法。

然后当我们要调用特定方法时,检查该方法是否被符合对象支持,如果是,则执行调用该方法所需的必要计算。例如,我尝试了此代码-

  @objc protocol FancyViewDelegate : NSObjectProtocol {
      optional func fancyView(view: UIView, didSelectSegmentAtIndex index: Int)
      optional func fancyView(view: UIView, shouldHighlightSegmentAtIndex index: Int) -> Bool
    }


    class FancyView: UIView {
      var delegate: FancyViewDelegate?

      private func somethingHappened() {
        if delegate?.respondsToSelector("fancyView:didSelectSegmentAtIndex") == true {
          let idx :Int  = 0 //Compute the index here
          delegate?.fancyView!(self, didSelectSegmentAtIndex: idx)
        }
      }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2017-01-22
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    相关资源
    最近更新 更多