2016-07-26 3 views
0

ВопросРазрешить только определенные классы, чтобы соответствовать протоколу в Swift

Я хотел бы создать протокол, который может быть реализован только определенным классом.

Пример

Допустим, есть протокол 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.

+0

почему не подкласс? – Wain

ответ

0

Fixed литьем с протоколом и с использованием другой переменной:

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 
    }