Roi Mulia
Roi Mulia

Reputation: 5896

Generic Class with Enum with associated values

I'm trying to create a generic UITableViewCell that inherits from an enum with associated values.
This is what I tried:

Enum declaration:

enum Content: Equatable  {
    case text(String)
    case image(UIImage)
    case error(Error)
    case indicator
}

And UITableViewCell declaration:

class MessageTableViewCell<T: Content>: UITableViewCell {
    var content: T?
}

But it fails with:

Type 'T' constrained to non-protocol, non-class type 'Content'

I'm trying to set up my cell with different types of "content view," depending on its content. Do note: I'm using XIB for the interface of the cell, so subclassing is not possible (I think). Any advice will be highly appreciated!

Upvotes: 1

Views: 78

Answers (1)

nutz
nutz

Reputation: 212

As per the error, you need to constrain it to either a protocol or a class. You can try the below code.

enum Content  {
    case text(String)
    case image(UIImage)
    case error(Error)
    case indicator
}

protocol CellContent {
    var content: Content { get set }
}

class MessageTableViewCell<T: CellContent>: UITableViewCell {
    var content: T?
}

Upvotes: 2

Related Questions