只允许某些 类 符合 Swift 中的协议

Allow only certain classes to conform protocol in Swift

问题

我想创建一个只能由某些class实现的协议。

例子

比方说,有一个协议X,所以只有classA可以符合它:

A:X

每个 X 都是 A,但不是每个 A 都是 X

实例

我想创建一个 CollectionViewCell 描述符来定义 CellClass,它的 reuseIdentifier 和可选的 value 将该描述符传递给控制器​​中的适当单元格:

协议

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

控制器

  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
  }

现在我需要强制转换以消除错误,因为 ConfigurableCollectionCell != UICollectionViewCell

通过转换为协议并使用另一个变量修复:

  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
  }