0
votes

I want to make a generic Datasource class, therefor I want that the generic conforms to a UITableViewCell and the protocol ViewModel at the same time.

protocol ViewModel class {
    associatedtype T
    var viewModel: T { get set }
}


class TableViewDatasourceStandard<G: UITableViewCell>: NSObject, UITableViewDataSource where G: ViewModel {
    let reUseIdentifier: String
    init( reUseIdentifier: String, cell: G) {
        self.reUseIdentifier = reUseIdentifier
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let row = indexPath.row
        let cell = tableView.dequeueReusableCell(withIdentifier: reUseIdentifier, for: indexPath) as! G
        cell.viewModel
        return cell
    }
}

I am getting the error:

Value of type 'G' has no member 'viewModel'

I tried some different stuff but I can not get it to work. Thanks!

1

1 Answers

1
votes

Instead of

protocol ViewModel class {
  associatedtype T
  var viewModel: T { get set }
}

You should write

protocol ViewModel {
  associatedtype T
  var viewModel: T { get set }
}

Remove class and it will work as expected.