2016-07-26 120 views
0

问题只允许某些类别的斯威夫特符合协议

我想创建只能由特定的类实现的协议。

比方说,有一个协议X,因此,只有一流的A能够符合它:

A:X 

XA,但不是每一个AX

实践例

我想创建一个CollectionViewCell描述符定义CellClass,其reuseIdentifier和可选value通该描述符到合适的细胞中的控制器:

协议

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

C ontroller

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

+0

为什么不是一个子类别? – Wain

回答

0

通过转换成协议,并使用另一个变量修正:

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 
    }