2016-07-26 26 views
0

FrageErlauben Sie nur bestimmte Klassen Protokoll in Swift

ich ein Protokoll erstellen möchte anzupassen, die nur von bestimmten Klasse implementiert werden können.

Beispiel

Lasst uns sagen, ist es ein Protokoll X, so dass nur Klasse A es anpassen kann:

A:X 

Jeder X ist A, aber nicht jedes A ist X.

Praktisches Beispiel

Ich mag würde einen CollectionViewCell Deskriptor zu schaffen, die CellClass definiert, dessen reuseIdentifier und optional value Pass, um geeignete Zellen in Controller descriptor:

Protocol

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 
    } 

Jetzt brauche ich Guss zu zwingen, von Fehlern zu befreien, wie ConfigurableCollectionCell != UICollectionViewCell.

+0

warum nicht eine Unterklasse? – Wain

Antwort

0

Fest durch zu Protokoll Gießen und unter Verwendung eines anderen 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 
    }