1

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!)

}
Anirudha Mahale
  • 2,526
  • 3
  • 37
  • 57

1 Answers1

1

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) }
    }
}
Daniel T.
  • 32,821
  • 6
  • 50
  • 72
  • This is actually the sub question from my previous question https://stackoverflow.com/questions/58050998/how-to-pass-data-from-delegate-method-to-the-observables-onnext-method-in-rxswi – Anirudha Mahale Sep 26 '19 at 11:59
  • So either am suppose to use `HasDelegate` protocol **OR** `setCurrentDelegate(_:to:)` & `currentDelegate(for:)` methods? – Anirudha Mahale Sep 26 '19 at 12:06
  • That is correct. All this information is in the docs for the DelegateProxyType by the way. Just look in its Swift file. – Daniel T. Sep 26 '19 at 13:56