简体   繁体   中英

Extend a delegate defined in a protocol with another protocol

I want to extend a protocol delegate with another protocol as follows:

protocol WriteableCallback: class {
  ...
}

protocol Writeable {
  weak var delegate: WriteableCallback? { get set }
}

protocol NetworkWriteablecallback: WriteableCallback {
  ...
}

protocol NetworkWriteable: Writeable {
  ..
}

Now implementing the NetworkWriteable is fairly straight forward:

final class DefaultNetworkWriteable: NetworkWriteable {
   weak var delegate: NetworkWriteablecallback? 
   //type 'DefaultNetworkWriteable' does not conform to protocol 'Writeable
   //because delegate should be of type 'Writeablecallback'
}

If i write

weak var delegate: Writeablecallback? 

everything compiles and works fine except that i can't call methods of NetworkWriteablecallback directly. I know, if i downcast the delegate like follows

if let delegate = delegate as? NetworkWriteablecallback {
 ...
}

than it works fine but casting isn't a good approach.

Any other suggestions?

Unfortunately, you can't "override" the delegate requirement declaration, and if you could I don't know that it would be a good thing.

I would provide a convenience for transparently casting the delegate. And with protocol extensions, this casting becomes an innate behavior of the NetworkWriteable protocol.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM