Leo
Leo

Reputation: 3143

How to define array of generic classes in swift

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?

Upvotes: 2

Views: 59

Answers (1)

GoZoner
GoZoner

Reputation: 70155

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]()

Upvotes: 1

Related Questions