Swift 使用委托(delegate)实现多个协议(protocol)

标签 swift delegates protocols

我正在尝试实现一个协议(protocol),该协议(protocol)本身继承了多个协议(protocol),这些协议(protocol)都有一个委托(delegate)成员。有没有一种干净的方法可以做到这一点,而不需要为每个协议(protocol)的委托(delegate)使用不同的名称?

protocol ProtocolOne {
    var delegate: ProtocolOneDelegate?
}

protocol ProtocolTwo {
    var delegate: ProtocolTwoDelegate?
}

protocol CombinedProtocol: ProtocolOne, ProtocolTwo {

}

protocol CombinedDelegate: ProtocolOneDelegate, ProtocolTwoDelegte {

}

class ProtocolImpl: CombinedProtocol {
    // How can I implement delegate here?
    // I've tried the following options without success:
    var delegate: CombinedDelegate?
    var delegate: protocol<ProtocolOneDelegate, ProtocolTwoDelegate>?
}

最佳答案

您应该能够将它们合二为一:

var delegate: (ProtocolOneDelegate & ProtocolTwoDelegate)?

您现在可以使用这两种协议(protocol)。

关于Swift 使用委托(delegate)实现多个协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27085158/

相关文章:

ios - 将委托(delegate)设置为对象

swift - View Controller 内的简单数据传输,无需转换

node.js - 如何使用 node.js 使用自定义协议(protocol)/方案定义路由?

swift - Facebook 共享对话框失败 - 操作无法快速完成

ios - 我如何将数据从 View Controller 传递到容器 View ?

java - 最好的 Java 支持的服务器/客户端协议(protocol)?

ios - 协议(protocol)的 Swift 实例

ios - Significant-Change Location Service 将使用 Wi-Fi 还是移动数据?

swift - Datasource为Results对象时如何用Realm做接口(interface)驱动写

ios - 一个 URLSession 中的不同超时