Swift使用委托实现多个协议

rob*_*era 3 delegates protocols swift

我正在尝试实现一个本身继承多个协议的协议,这些协议都有一个委托成员.是否有一种干净的方法来执行此操作而不需要为每个协议的委托使用不同的名称?

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>?
}
Run Code Online (Sandbox Code Playgroud)

Tra*_* M. 12

你应该能够把它们合二为一:

var delegate: (ProtocolOneDelegate & ProtocolTwoDelegate)?
Run Code Online (Sandbox Code Playgroud)

您现在可以使用这两种协议.


Ant*_*nio 2

在您的代码中,delegate只是一个普通属性。您可以使用多个协议来声明具有相同名称和相同类型的属性,并让一个类直接或间接实现它。

如果不同的协议定义了具有相同名称但不同类型的属性,则将无法使其编译,因为编译器会抱怨重新声明属性和类不符合其中一种协议。

有2种可能的解决方案。最明显的一个是避免使用在其他协议中使用的可能性很高的名称 - 这delegate是一个典型的案例。使用不同的命名约定,例如protocol1DelegatedataSourceDelegateapiCallDelegate等。

第二个解决方案包括用方法替换属性。例如:

protocol P1 {
    func test() -> String?
}

protocol P2 {
    func test() -> Int?
}

protocol P3: P1, P2 {

}

class Test : P3 {
    func test() ->  String? { return nil }
    func test() -> Int? { return nil }
}
Run Code Online (Sandbox Code Playgroud)

Swift 将具有相同参数列表但不同返回类型的函数视为重载。但请注意,如果两个协议使用相同的函数签名(名称、参数和返回类型),则在类中实现时,您将实现该函数一次 - 这在某些情况下可能是所需的行为,但在其他情况下则不需要。