我知道这篇文章与我有同样的问题,但是没有答案而且很旧,所以我想在这里刷新它。
//: Playground - noun: a place where people can play
import UIKit
protocol BaseViewModel { }
protocol SomeCellViewModelInterface : BaseViewModel { }
protocol AnotherCellViewModelInterface : BaseViewModel { }
protocol BaseCell {
typealias T
func configure(viewmodel: T)
}
//
class someCell : UIView, BaseCell {
typealias T = SomeCellViewModelInterface
func configure(viewmodel: T) {
// awesome
}
}
class someOtherCell : UIView, BaseCell {
typealias T = AnotherCellViewModelInterface
func configure(viewmodel: T) {
// do stuff
}
}
// the concrete implementations of viewmodels and actually using this UI is ultimatley in another .framework
class ConcreteSomeCellVM : SomeCellViewModelInterface { }
class ConcreteAnotherCellVM : AnotherCellViewModelInterface { }
var viewModel = ConcreteSomeCellVM()
let views: [UIView] = [someCell(), someOtherCell(), UIView()]
这是我需要的一个基本示例,但它说明了这一点
for v in views {
// A
if let cell = v as? someCell {
cell.configure(viewModel)
}
// B
if let cell = v as? BaseCell {
cell.configure(viewModel)
}
}
块 A 有效,但需要知道具体的单元格类,所以如果我有许多不同单元格的列表,一些我不知道具体类型的单元格将不起作用。
块 B 抛出此错误:
错误:协议“BaseCell”只能用作通用约束,因为它具有 Self 或关联的类型要求
有没有办法可以实现Block B?