我想用另一个协议扩展协议委托如下:
protocol WriteableCallback: class {
...
}
protocol Writeable {
weak var delegate: WriteableCallback? { get set }
}
protocol NetworkWriteablecallback: WriteableCallback {
...
}
protocol NetworkWriteable: Writeable {
..
}
现在实施NetworkWriteable非常简单:
final class DefaultNetworkWriteable: NetworkWriteable {
weak var delegate: NetworkWriteablecallback?
//type 'DefaultNetworkWriteable' does not conform to protocol 'Writeable
//because delegate should be of type 'Writeablecallback'
}
如果我写
weak var delegate: Writeablecallback?
除了我不能直接调用NetworkWriteablecallback的方法之外,所有内容都编译并正常工作。我知道,如果我贬低代表如下
if let delegate = delegate as? NetworkWriteablecallback {
...
}
比它工作正常,但铸造不是一个好方法。
还有其他建议吗?
答案 0 :(得分:0)
不幸的是,you can't "override" delegate
要求声明,如果您可以,我不知道这将是一件好事。
我会为透明地转换委托提供便利。通过协议扩展,此转换成为NetworkWriteable
协议的固有行为。
extension NetworkWriteable {
var networkWriteableDelegate: NetworkWriteablecallback? {
set {
delegate = newValue
}
get {
return delegate as? NetworkWriteablecallback
}
}
}
final class DefaultNetworkWriteable: NetworkWriteable {
weak var delegate: WriteableCallback?
func myfunc() {
if self.networkWriteableDelegate === self.delegate {
// always true
}
}
}