Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Issue, any Suggestions?

// UITableView+.Swift Extension

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
  }
}

My question is, why I need to do let t = model as! T.CellType.ModelType this in UITableView Extension instead of just passing the model to setupModel(model: ModelType) function.

like image 971
Teenenggr Avatar asked Feb 03 '26 06:02

Teenenggr


1 Answers

You need to add the constraint CellType.ModelType == Self to CellViewModel

protocol CellViewModel where Self: NSObject, CellType: ReusableCell, CellType.ModelType == Self {
    associatedtype CellType
}
like image 183
Johannes Avatar answered Feb 05 '26 22:02

Johannes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!