代码之家  ›  专栏  ›  技术社区  ›  Richard Topchii

阵列中具有关联类型的协议-替代解决方案

  •  0
  • Richard Topchii  · 技术社区  · 6 年前

    protocol CellConfigurator {
      var cellClass: UICollectionViewCell.Type {get}
      func configure(cell: UICollectionViewCell)
    }
    
    class AppleCell: UICollectionViewCell {
      let title = UILabel()
    }
    
    class AppleCellConfigurator: CellConfigurator {
      let cellClass: UICollectionViewCell.Type = AppleCell.self
      func configure(cell: UICollectionViewCell) {
        guard let cell = cell as? AppleCell else {return}
        cell.title.text = "AAPL"
      }
    }
    

    UICollectionViewCell ,请按如下方式使用(伪代码):

    func cellAt(indexPath: IndexPath) -> UICollectionViewCell {
      let configurator = configurators[indexPath]
      let cell = collectionView.dequeueReusableCell(identifier: String(describing: configurator.cellClass))
      configurator.configure(cell)
      return cell
    }
    

    我期待着摆脱在每一个符合 CellConfigurator

    protocol CellConfigurator {
      associatedtype Cell
      func configure(cell: Cell)
    }
    
    class AppleCell: UICollectionViewCell {
      let title = UILabel()
    }
    
    class AppleCellConfigurator: CellConfigurator {
      typealias Cell = AppleCell
      func configure(cell: Cell) {
        cell.title.text = "AAPL"
      }
    }
    

    但是,由于一个错误,我无法将它们组合在一个数组中:“协议‘SomeProtocol’只能用作泛型约束,因为它具有自身或关联的类型需求”。

    有没有办法实现这两个目标:

    1. 有功能的 UICollectionViewCell 任何 细胞配置器
    2. 在一个特定的配置器的功能中有一个具体的类型
    1 回复  |  直到 6 年前
        1
  •  0
  •   shio    6 年前

    您可以在CellConfigurator中使用associatedtype:

    protocol CellConfigurator: class {
        associatedtype CellType where CellType: UICollectionViewCell
    
        func configure(cell: CellType)
    }
    
    class AppleCell: UICollectionViewCell {
        let title = UILabel()
    }
    
    class AppleCellConfigurator: CellConfigurator {
        typealias CellType = AppleCell
    
        func configure(cell: CellType) {
            cell.title.text = "AAPL"
        }
    }