Create generic object with subclass as parameter

Greetings.

I have run up against another generic brick wall, so to speak.

I have a generic class:

class Thing<ownerT>
{
  private var owner: ownerT
  
  init(owner: ownerT)
  {
    self.owner = owner
  }
}

Now I would like to use that type inside a generic protocol:

public protocol Owner
{
  var thing: Thing<Self> { get set }
}

Next, I would like to implement that protocol in a hierarchy of classes, such that the "owner" passed to the generic class is the current subclass:

class Base : Owner
{
  var thing: Thing<Self> // meant to allow use of Derived but obviously this won't compile
}

class Derived : Base
{
}

Problem 1: the use of Self in the protocol makes its compulsory to use a final class to implement the protocol.

Problem 2: derived classes need to use Thing<…> as if it belonged to their concrete type, not Base.

Any bright ideas how I can get Derived to see Thing ?

If this were C#, I could bind the generic type to something akin to type(of: self)

But this is Swift and I am struggling with the lack of dynamicism :roll_eyes:

Terms of Service

Privacy Policy

Cookie Policy