只允许某些类别的斯威夫特符合协议
问题描述:
我想创建只能由特定的类实现的协议。
例
比方说,有一个协议X
,因此,只有一流的A
能够符合它:
A:X
每X
为A
,但不是每一个A
是X
。
实践例
我想创建一个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
。
答
通过转换成协议,并使用另一个变量修正:
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
}
为什么不是一个子类别? – Wain