Hello everyone, I am trying to do a generic protocol for a collection view with different types of cell and data objects. For example, I have a list of items : var items: [AnyObject]!
. So, I create a protocol like this :
protocol DKCardConfiguratorProtocol {
associatedtype Item
func configure(item: Item)
static var reuseIndentifier: String { get }
}
extension DKCardConfiguratorProtocol {
static var reuseIndentifier: String {
//By default I use the class's name as an identifier
return String(Self)
}
}
In my collection view data source class :
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let item = self.items[indexPath.row]
switch item {
case let fidData as DKFidelityCardData:
let cell = collectionView.dequeueReusableCell(indexPath: indexPath) as DKFidelityCardCell
cell.configure(fidData)
default:
fatalError("Data type not handled")
}
}
An example of a cell :
class DKFidelityCardCell: UICollectionViewCell, DKCardConfiguratorProtocol {
func configure(item: DKFidelityCardData) {
print("Configuring DKFidelityCardCell")
}
}
What do you think about this ? Is it a good approach ?