0

I am trying to use RxSwift/RxDataSource with TableView but I am not able to assign configureCell with an existing function. Code below:

import UIKit
import RxSwift
import RxCocoa
import RxDataSources

class BaseTableViewController: UIViewController {
    // datasources
    let dataSource = RxTableViewSectionedReloadDataSource<TableSectionModel>()
    let sections: Variable<[TableSectionModel]> = Variable<[TableSectionModel]>([])
    let disposeBag: DisposeBag = DisposeBag()

    // components
    let tableView: UITableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setDataSource()
    }

    func setupUI() {
        attachViews()
    }

    func setDataSource() {
        tableView.delegate = nil
        tableView.dataSource = nil
        sections.asObservable()
            .bindTo(tableView.rx.items(dataSource: dataSource))
            .addDisposableTo(disposeBag)
        dataSource.configureCell = cell
        sectionHeader()
    }

    func cell(ds: TableViewSectionedDataSource<TableSectionModel>, tableView: UITableView, indexPath: IndexPath, item: TableSectionModel.Item) -> UITableViewCell! {
        return UITableViewCell()
    }

    func sectionHeader() {

    }
}

Xcode throws the following error:

/Users/.../BaseTableViewController.swift:39:36: Cannot assign value of type '(TableViewSectionedDataSource, UITableView, IndexPath, TableSectionModel.Item) -> UITableViewCell!' to type '(TableViewSectionedDataSource, UITableView, IndexPath, TableSectionModel.Item) -> UITableViewCell!'

the error is thrown at line

dataSource.configureCell = cell

Do you have any idea?

Thanks

Keldon
  • 192
  • 1
  • 10

1 Answers1

0

You just need to remove ! from return type UITableViewCell! of your cell method.

func cell(ds: TableViewSectionedDataSource<TableSectionModel>, tableView: UITableView, indexPath: IndexPath, item: TableSectionModel.Item) -> UITableViewCell {
    return UITableViewCell()
}

In this way your function became type compatible with type expected by RxDataSource's configureCell property:

public typealias CellFactory = (TableViewSectionedDataSource<S>, UITableView, IndexPath, I) -> UITableViewCell

I, personally, prefer the following syntax for initialising configureCell:

dataSource.configureCell = { (_, tableView, indexPath, item) in
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    // Your configuration code goes here
    return cell
}
ixrevo
  • 96
  • 3