Wazza
Wazza

Reputation: 1885

Class conform to protocol with function that receives a generic parameter

I have two data structs and both conform to a protocol CellDataType:

enum CellType {
  case picture
  case text
}

protocol CellDataType {
   var type: CellType { get }
}

struct PictureData: CellDataType {
   var type: CellType = .picture
   let image: UIImage
}

struct TextData: CellDataType {
   var type: CellType = .picture
   let text: String
}

What i would like to do is have a multiple classes that conform to a protocol that receives this data type then conform by using the specific dat to that cell Like so:

protocol VariableCell {
   func setUp<T: CellDataType>(cellData: T)
}

class PictureCell: VariableCell {
   func setUp(cellData: PictureData) {
   }
}

class TextCell: VariableCell {
   func setUp(cellData: TextData) {
   }
}

Is this possible?

Apologies if this is im struggling to know what to google

Upvotes: 0

Views: 42

Answers (1)

Rob Napier
Rob Napier

Reputation: 299265

The code you've written can't be correct because VariableCell requires that any CellDataType be passable to setUp, but then PictureCell only permits one specific types to be passed. If you passed a VariableCell to a function, what would it have to pass to setUp?

But if you're really trying to express that PictureCell conforms to VariableCell by setting T == PictureData (rather than by VaraibleCell accepting all possible T), then that's exactly what associatedtypes are for:

protocol VariableCell {
   associatedType CellData: CellDataType
   func setUp(cellData: CellData)
}

class PictureCell: VariableCell {
   func setUp(cellData: PictureData) {
   }
}

class TextCell: VariableCell {
   func setUp(cellData: TextData) {
   }
}

Once you do this, you can no longer use VariableCell as a normal type. For example, you cannot have a [VariableCell], because you would not be able to loop over them and call setUp (what would you pass if the types can be different)? But assuming that you intend to build generic code that relies on VariableCell, then this is exactly the tool you want.

Upvotes: 1

Related Questions