假设我们在 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 let
或guard let
绑定两个具有相似前缀签名的可选方法的实现。