簡體   English   中英

如果符合 X 的 class 是可散列的,我如何將一組協議 X 轉換為“可散列”?

[英]How can I cast a an array of protocol X to `Hashable` if the class conform to X is Hashable?

我的 TableView 單元控制器也有一個協議:

protocol TableViewCellController {
  func view(in tableView: UITableView) -> UITableViewCell
  func cancelLoad()
  func prefetch()
}

extension TableViewCellController {
  func prefetch() { }
}

由於我的表格視圖呈現多種單元格類型,每種類型的項目都作為自己的 controller


final class ContentArticleTitleCellController: TableViewCellController {

  private var cell: ContentArticleTitle?

  func view(in tableView: UITableView) -> UITableViewCell {
    cell = tableView.dequeueReusableCell()
    return cell!
  }
.....
}

final class ContentArticleSummaryCellController: TableViewCellController {

  private var cell: ContentArticleSummary?

  func view(in tableView: UITableView) -> UITableViewCell {
    cell = tableView.dequeueReusableCell()
    return cell!
  }
.....
}

由於所有這些控制器都符合Hashable ,我想使用UITableViewDiffableDataSource

我可以像這樣使用AnyHashable創建我的數據源

  func makeDataSource() -> UITableViewDiffableDataSource<Section, AnyHashable> {
    return UITableViewDiffableDataSource(tableView: tableView) { tv, indexPath, controller -> UITableViewCell? in
      guard let controller = controller as? TableViewCellController else { return nil }
      return controller.view(in: tv)
    }
  }

我不確定如何將我的[TableViewCellController]轉換為[AnyHashable]但是因為TableViewCellController不符合它,而是符合它的 class 。

我曾考慮過

  func update(with items: [TableViewCellController], animate: Bool = true) {
    let controllers = items.compactMap { $0 as? AnyHashable }
  }

但由於這些類型不相關,它總是失敗。

如果我嘗試

let controllers = items.compactMap { $0 as? Hashable }

然后我點擊了generic constraint because it has Self or associated type requirements

當然我可以做類似的事情

let controllers = items.compactMap { $0 as? ContentArticleSummaryCellController }

但是如果我有 30 個不同的單元格 controller 類型,這會變得混亂

我怎樣才能做到這一點?

你很接近這種方法:

let controllers = items.compactMap { $0 as? AnyHashable }

將其更改為:

let controllers = items.map(AnyHashable.init)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM