【问题标题】:Swift, implement same delegate two times (without multicast) [duplicate]Swift,两次实现相同的委托(没有多播)[重复]
【发布时间】:2018-12-03 20:55:07
【问题描述】:

给定一个非常简单的协议:

protocol TheProtocol {
    func doSomething()
    func doSomethingElse()
    func doThis()
    func doThat()
}

我有一个类 Base 有一个等待设置的委托。

// Can't modify this class at all
class Base  {
    public var delegate: TheProtocol?
}

我的第二个类B 继承自这个类Base,并实现TheProtocol 以便将委托设置为自身。

class B: Base, TheProtocol {

    override init() {
        super.init()
        self.delegate = self
    }

    func doSomething() {

    }
    func doSomethingElse() {

    }
    ... other methods to implement
}

现在我想要做的是有一个最后一个类C,它包含一个B 的实例,并且还设置了委托。我希望代表在 BC 内部工作。

主要的限制是我不能修改Base 类。

class C: TheProtocol {

    var obj = B()

    init() {
        // If I do this it won't fire within B anymore
        obj.delegate = self
    }

    func doSomething() {

    }
    func doSomethingElse() {

    }
    ... other methods to implement
}

【问题讨论】:

  • 必须编写 B 类来代理委托,以便它可以处理调用并代表“真实”委托调用协议方法。
  • @RobertDresler 正如我提到的,我不能修改第一类并进行多播,它在标题中
  • @rmaddy,所以如果我的协议有 25 个方法,我需要全部覆盖它们,完成工作,然后在内部调用我的新委托?
  • 这是一种方式。但显然这将是 25 种方法的混乱。我建议它是因为您显示的是 1,而不是 25。
  • @rmaddy 不幸的是,我将其作为一个简化示例。实际上,我正在处理 UICollectionViewDelegate...

标签: swift delegates


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多