Search code examples
rx-swiftrx-cocoa

How to write getter and setter for HasDelegate protocol in RxSwift?


I am implementing HasDelegate protocol to the IWDeviceManager.

In all the posts which I have read, no one has wrote getter & setter for this public var delegate property.

The compiler is explicitly asking me to write getter & setter for public var delegate. Why it's required in my case?

I tried writing but my code crashes when I try to get or set the delegate.

How do I solve this issue?

I have shared the code below

extension IWDeviceManager: HasDelegate {

    public typealias Delegate = IWDeviceManagerDelegate

    // Compiler explicitly asks to write getter and setter for this.
    public var delegate: IWDeviceManagerDelegate? { 
        get { // Crashes here
            return IWDeviceManager.shared()?.delegate 
        } 
        set(newValue) { // crashes here
            IWDeviceManager.shared()?.delegate = newValue 
        } 
    }
}

Below is interface for IWDeviceManager

open class IWDeviceManager : NSObject {

    weak open var delegate: IWDeviceManagerDelegate!

    open class func shared() -> Self!

    open func initMgr()

    open func initMgr(with config: IWDeviceManagerConfig!)

}

Solution

  • Instead of using HasDelegate try this:

    class IWDeviceManagerDelegateProxy
        : DelegateProxy<IWDeviceManager, IWDeviceManagerDelegate>
        , DelegateProxyType
        , IWDeviceManagerDelegate {
    
        init(parentObject: IWDeviceManager) {
            super.init(parentObject: parentObject, delegateProxy: IWDeviceManagerDelegateProxy.self)
        }
    
        static func currentDelegate(for object: IWDeviceManager) -> Delegate? {
            return object.delegate
        }
    
        static func setCurrentDelegate(_ delegate: IWDeviceManagerDelegate?, to object: IWDeviceManager) {
            object.delegate = delegate
        }
    
        static func registerKnownImplementations() {
            self.register { IWDeviceManagerDelegateProxy(parentObject: $0) }
        }
    }