0

Question

I would like to create a protocol that can be implemented only by certain class.

Example

Let's say, there is a protocol X, so that only class A can conform to it:

A:X

Every X is A, but not every A is X.

Practical Example

I would like to create a CollectionViewCell descriptor which defines CellClass, its reuseIdentifier and optional value pass that descriptor to appropriate cells in controller:

Protocol

protocol ConfigurableCollectionCell { // Should be of UICollectionViewCell class
  func configureCell(descriptor: CollectionCellDescriptor)
}

Controller

  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let descriptor = dataSource.itemAtIndexPath(indexPath)
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(descriptor.reuseIdentifier, forIndexPath: indexPath) as! ConfigurableCollectionCell
    cell.configureCell(descriptor)
    return cell as! UICollectionViewCell
  }

Now I need to force cast to get rid of errors, as ConfigurableCollectionCell != UICollectionViewCell.

Richard Topchii
  • 7,075
  • 8
  • 48
  • 115

1 Answers1

0

Fixed by casting to protocol and using another variable:

  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let descriptor = dataSource.itemAtIndexPath(indexPath)

    // Cast to protocol and configure
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(descriptor.reuseIdentifier, forIndexPath: indexPath)
    if let configurableCell = cell as? ConfigurableCollectionCell {
      configurableCell.configureCell(descriptor)
    }
    // Return still an instance of UICollectionView
    return cell
  }
Richard Topchii
  • 7,075
  • 8
  • 48
  • 115