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

Вопрос

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

Пример

Допустим, есть протокол X, так что ему может соответствовать только класс A:

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
  }

Теперь мне нужно заставить cast избавиться от ошибок, так как ConfigurableCollectionCell != UICollectionViewCell.


person Richard Topchii    schedule 26.07.2016    source источник
comment
почему не подкласс?   -  person Wain    schedule 26.07.2016


Ответы (1)


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

  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
  }
person Richard Topchii    schedule 26.07.2016