Search code examples
iosobjective-cswiftdelegatesextend

Extending a delegate from a base class


I have an objc base class:

@protocol BaseClassDelegate;

@interface BaseClass : NSObject

@property (nonatomic, weak) id <BaseClassDelegate> delegate;

@end

@protocol BaseClassDelegate <NSObject>

-(void)baseDelegateMethod;

@end

I am creating a swift sub-class in which I want to extend my delegate...

protocol SubClassDelegate : BaseClassDelegate {

    func additionalSubClassDelegateMethod();
}

class SubClass: BaseClass {

    @IBAction func onDoSomething(sender: AnyObject) {

        delegate?.additionalSubClassDelegateMethod();  <--- No such method in 'delegate'
    }
}

Now, when I create my sub-class, I can say it conforms to the SubClassDelegate and set the delegate. The problem is (of course), is that 'delegate' doesn't exist in this sub-class. Is there a way to tell the compiler to 'extend' my delegate into my sub-class? (or am I being insane here and missed something obvious)


Solution

  • I'd either create a wrapper delegate to make it the correct type in SubClass.

    class SubClass: BaseClass {
        var myDelegate: SubClassDelegate? {
            get { return delegate as? SubClassDelegate }
            set { delegate = newValue }
        }
        @IBAction func onDoSomething(sender: AnyObject) {
            myDelegate?.additionalSubClassDelegateMethod();
        }
    }
    

    Or simply cast the delegate to the expected type:

    (delegate as? SubClassDelegate)?.additionalSubClassDelegateMethod();