// UITableView + .Swift扩展
extension UITableView {
func cellForModel<T: CellViewModel>(at: IndexPath, model: T) -> T.CellType {
let cell: T.CellType = dequeueReusableCell()
*let t = model as! T.CellType.ModelType*
cell.setupModel(model: t)
return cell
}
func dequeueReusableCell<T: ReusableCell>() -> T {
print(T.reuseIdentifier())
let temp = self.dequeueReusableCell(withIdentifier: T.reuseIdentifier())
return temp as! T
}
}
// CellViewModel.Swift
protocol CellViewModel where Self: NSObject, CellType: ReusableCell {
associatedtype CellType
}
// ReusableCell.Swift
protocol ReusableCell where Self: UITableViewCell, ModelType: CellViewModel {
associatedtype ModelType
static func reuseIdentifier() -> String
func setupModel(model: ModelType)
var cell: UITableViewCell { get }
}
extension ReusableCell {
static func reuseIdentifier() -> String {
return String(describing: Self.self)
}
var cell: UITableViewCell {
return self as UITableViewCell
}
}
我的问题是,为什么我需要在UITableView Extension中对此进行
let t = model as! T.CellType.ModelType
而不是仅仅将模型传递给setupModel(model: ModelType)
函数。 最佳答案
您需要将约束CellType.ModelType == Self
添加到CellViewModel
protocol CellViewModel where Self: NSObject, CellType: ReusableCell, CellType.ModelType == Self {
associatedtype CellType
}