![](/img/trans.png)
[英]How can I cast an array of [AnyObject] to an array of [Hashable] or [AnyHashable] in Swift?
[英]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.