代码之家  ›  专栏  ›  技术社区  ›  PaFi

泛型符合协议和类(uitableviewcell)

  •  0
  • PaFi  · 技术社区  · 8 年前

    我想创建一个泛型数据源类,因此我希望泛型同时符合uitableviewcell和protocol viewmodel。

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

    我发现了错误:

    类型“g”的值没有成员“viewmodel”

    我试了一些不同的东西,但是我没法用。谢谢!

    1 回复  |  直到 8 年前
        1
  •  1
  •   trungduc 邱林和    8 年前

    而不是

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

    你应该写信

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

    删除 class 它将如预期的那样工作。