2

I have several classes for cells data with CellDataBase as base class. Main idea is that I can define new cell data class and pair it with cell by generic.

public class CellBase { }

public class CellA: CellBase { }

public class CellB: CellBase { }


public class CellDataBase<U: CellBase> {
    var cellType: U.Type = U.self
}

class CellDataA: CellDataBase<CellA> { }

class CellDataB: CellDataBase<CellB> { }

Is it possible to define array and store CellDataA, CellDataB etc. in it?

1 Answer 1

1

No, it is not possible because there is no common type ancestor to CellDataA and CellDataB. You might think that CellDataBase is a common ancestor but it is not; the introduction of the U type parameter means that for each type U there is a totally distinct type.

You might try something like this:

protocol CellDataBase {
  // avoid `Self` and `associatedType`
  // ...

  var count : UInt { get } // number of items in database..

  // ...
}

public class StandardCellDataBase<U: CellBase> : CellDataBase { ... }
class CellDataA: StandardCellDataBase <CellA> { }
class CellDataB: StandardCellDataBase <CellB> { }

and then:

var databases = [CellDataBase]()

Note that defining CellDataBase as a protocol that avoid "Self and associated types requirements" might be difficult, depending on your needs.

====

Another similar option, assuming you can't change your definition of CellDataBase is to define another protocol and add it as an extension to CellDataBase. Like such:

protocol GenericCellDataBase {
  var count : UInt { get }
}

extension CellDataBase : GenericCellDataBase {
  var count : UInt { return ... }
}

var databases = [GenericCellDataBase]()
Sign up to request clarification or add additional context in comments.

1 Comment

Nice point, I'd replaced protocol CellDataBase to class CellDataBase and it also works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.