繁体   English   中英

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

[英]Protocols with Associated Types in array - alternative solutions

考虑一个例子:

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"
  }
}

但是,由于错误,我无法将它们放在一个数组中:“ Protocol'SomeProtocol'只能用作通用约束,因为它具有Self或关联的类型要求”。

有什么方法可以实现两个目标:

  1. UICollectionViewCell对任何CellConfigurator具有UICollectionViewCell参数类型的CellConfigurator
  2. 在特定配置器的功能内具有具体类型

您可以在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"
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM