gpt4 book ai didi

swift - 在 Swift 中向现有协议(protocol)添加函数签名

转载 作者:行者123 更新时间:2023-11-30 11:41:13 24 4
gpt4 key购买 nike

我们有一个包含许多 NSCollectionViews 的大型代码库,我们希望添加一个功能来使用键盘控制 View ,同时更改尽可能少的代码。

为此,我们希望处理一个文件中的 key ,并通过委托(delegate)协议(protocol)简单地触发“Action Fired”事件。我们的 NSCollectionView 已经实现了 NSCollectionViewDelegate 协议(protocol),因此我们希望将事件直接添加到该协议(protocol),而不是通过继承来完成。

现在,我知道您可以使用 extension 关键字来扩展协议(protocol):

extension NSCollectionViewDelegate {
func collectionView(_ collectionView: NSCollectionView, didMoveLeft: Bool) {
// Default implementation here
}
}

这种方法的问题在于,由于签名尚未在原始协议(protocol)中声明,因此即使类实现了自己的实现,也始终会调用默认实现。

那么,真正扩展协议(protocol)功能的最佳方法是什么,以便我现有的所有 NSCollectionViews 都能够实现自己的行为,而无需子类化 协议(protocol)

到目前为止,我发现“最好的方法”是编写以下内容:

extension NSCollectionView {
override open func moveLeft(_ sender: Any?) {
(delegate as? NSCollectionViewDelegateExtended)?.collectionView(self, didMoveLeft: true)
}
}

protocol NSCollectionViewDelegateExtended : NSCollectionViewDelegate {
func collectionView(_ collectionView: NSCollectionView, didMoveLeft: Bool)
}

然后实现 NSCollectionViewDelegateExtended 而不是 NSCollectionViewDelegate:

extension CustomViewController: NSCollectionViewDelegateExtended {
func collectionView(_ collectionView: NSCollectionView, didMoveLeft: Bool) {
// Implementation here
}
}

但这并不是我想要的。是否有更好的方法将该新函数无缝嵌入 NSCollectionViewDelegate 中?

最佳答案

一种解决方案是将新的委托(delegate)方法添加为可选。请记住,为了执行此操作,您必须打开 objective-C 协议(protocol)。这可以像下面这样完成

@objc protocol MyProtocol {
//older method 1
//older method 2
//...
//older method X

@objc optional func newMethod()
}

关于swift - 在 Swift 中向现有协议(protocol)添加函数签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49269646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com