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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了阵列中具有关联类型的协议 - 替代解决方案相关的知识,希望对你有一定的参考价值。

考虑一个例子:

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'只能用作通用约束,因为它具有Self或相关类型要求”。

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

  1. 有任何UICollectionViewCellCellConfigurator参数类型的函数?
  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"
    }
}

以上是关于阵列中具有关联类型的协议 - 替代解决方案的主要内容,如果未能解决你的问题,请参考以下文章

使用 swinject 注册具有关联类型的协议时出现问题

通过指定类型将“具有关联类型的协议”转换为常规协议

Swift 协议扩展实现另一个具有共享关联类型的协议

7.多关联双亲染色体片段代换系(CSSL)群体的代谢组分析

“协议......只能用作通用约束,因为它具有 Self 或关联的类型要求”是啥意思?

“协议......只能用作通用约束,因为它具有 Self 或关联的类型要求”是啥意思?