使用其他协议扩展协议中定义的委托

时间:2017-07-19 12:32:09

标签: ios swift3

我想用另一个协议扩展协议委托如下:

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 {
 ...
}

比它工作正常,但铸造不是一个好方法。

还有其他建议吗?

1 个答案:

答案 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
        }
    }
}