Swift协议一致性问题

时间:2020-06-08 22:55:40

标签: ios swift protocols

我有2个协议和一个符合该协议的类。

protocol SomeProtocol: AnyObject { }

protocol AnotherProtocol: AnyObject { }

protocol HelperProtocol {
  var delegate: AnotherProtocol? { get }
}

class SomeClass {
  weak var delegate: (SomeProtocol & AnotherProtocol)?
}

extension SomeClass: HelperProtocol { // Type 'SomeClass' does not conform to protocol 'HelperProtocol'

}

如何解决编译错误?

1 个答案:

答案 0 :(得分:0)

Swift 不支持并没有根本原因,但是(到目前为止)它不支持。 This answer做得很好。

不幸的是,我认为最好的解决方案是制作两个属性。

class SomeClass: HelperProtocol {
  weak var strictlyTypedDelegate: (SomeProtocol & AnotherProtocol)?
  var delegate: AnotherProtocol? { strictlyTypedDelegate }
}