carlbenson
carlbenson

Reputation: 3207

Allowing a subclass to use a subclassed delegate

I am trying to achieve a clean OOP structure to a problem in Swift. It seems like it should be possible with Swift 1.2 and Apple's new embracing of Protocol Oriented Programming.

I have a class A that has its own delegate ADelegate. A itself makes calls to methods of ADelegate.

Two subclasses inherit A: B and C. B has some delegated methods that only it should be able to call, so it wants its own delegate, BDelegate, which inherits ADelegate and adds a few methods. Similarly, C wants its delegate to be CDelegate, which inherits ADelegate and adds some methods.

The cleanest way to structure this would be give A a property var delegate: ADelegate. Then, somehow, B and C get properties override var delegate: BDelegate and override var delegate: CDelegate respectively. That way they can both use methods ADelegate exposes as well as their own particular implementations. However, Swift doesn't let me compile that because I cannot override a property and assign it a different type.

I know that I can create a different named delegate property on the subclasses so there is no conflict. I also know that I can have the child classes cast the delegate, but that is an expensive operation and not very clean.

It feels like their should be a protocol-oriented way of handling this. To sum up, the goal is to allow subclasses to override properties of superclasses with more specific types. Any ideas?

Upvotes: 2

Views: 145

Answers (1)

GoZoner
GoZoner

Reputation: 70155

You want subclasses of A to have subclass-specific delegates; you achieve this with generics:

//
// A Stuff
//
class ADelegate {
  func doAnAThing () {}
}

class A<Delegate:ADelegate> {
  var delegate : Delegate?
}

//
// B Stuff
//
class BDelegate: ADelegate {
  func doABThing () {}
}

class B : A<BDelegate> {      
}

This example with class applies to the other Swift abstraction styles as well.

Upvotes: 4

Related Questions