RxSwift - Generic parameter 'Self' could n

2020-04-25 23:55发布

问题:

I have an UITableView and a countries variable whose signature is like:

let countryArray = ["Bangladesh", "India", "Pakistan", "Nepal", "Bhutan", "China", "Malaysia", "Myanmar", "Sri Lanka", "Saudi Arabia"]

When I'm trying to bind this array of countries in a UITableView, Its showing the error Generic parameter 'Self' could not be inferred.

Here is the snippet that I am doing:

let countries = Observable.just(countryArray)
    countries.bindTo(self.tableView.rx.items(cellIdentifier: "myCell",
                                        cellType: MyCell.self)) {
                                            row, country, cell in
                                            // configuring cell
    }
    .addDisposableTo(disposeBag)

回答1:

I would suggest you to use the latest version of RxSwift. What you're using right now is deprecated. Your error may be related to it.

There are two ways to do what you're doing:

let countryArray = ["Bangladesh", "India", "Pakistan", "Nepal", "Bhutan", "China", "Malaysia", "Myanmar", "Sri Lanka", "Saudi Arabia"]
let countries = Observable.of(countryArray)

// Be sure to register the cell
tableView.register(UINib(nibName: "MyCell", bundle: nil), forCellReuseIdentifier: "myCell")
  1. To provide the cell type in the items(cellIdentifier:cellType:), that's basically what you are doing:

    countries
        .bind(to: tableView.rx.items(cellIdentifier: "myCell", cellType: MyCell.self)) { (row, element, cell) in
            // configure cell
        }
        .disposed(by: disposeBag)
    
  2. To provide the cell factory closure, in other words dequeue the cell in the closure and return it:

    countries
        .bind(to: tableView.rx.items) { (tableView, row, element) in
            let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: IndexPath(row: row, section: 0)) as! MyCell
            // configure cell
            return cell
        }
        .disposed(by: disposeBag)
    

Both have pros and cons. The second one has a reference to the tableView which sometimes can be very handy.