How do I create two table views in one view controller with two custom UITableViewCells?

The error appears because if for any reason, the table view is non of the two options that you wrote, then it doesn't have any value to return, just add a default value at the end:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView == firstTableView,
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomOne") as? CustomOneTableViewCell {
        return cell
    } else if tableView == autoSuggestTableView,
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTwo") as? CustomTwoTableViewCell {
        return cell
    }

    return UITableViewCell()
}

Updated to swift 4.1.2: I've updated this answer to version 4.1.2, also, because the return value of the method cannot be nil, modified to a default, dummy UITableViewCell.


Your issue is that the compiler looks at the possibility that both if statements might be false and you don't return anything in that case, hence the error.

If you only have the two tables, the easiest change is this:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if tableView == self.tableView {
        let cell = tableView.dequeueReusableCellWithIdentifier("CustomOne") as! CustomOneTableViewCell
        return cell
    } else {
        let cell = tableView.dequeueReusableCellWithIdentifier("CustomTwo") as! CustomTwoTableViewCell
        return cell
    }
}

My preferred solution to this problem would be to do the following:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cellToReturn = UITableViewCell() // Dummy value
    if tableView == self.tableView {
        let cell = tableView.dequeueReusableCellWithIdentifier("CustomOne") as! CustomOneTableViewCell
        cellToReturn = cell
    } else if tableView == self.autoSuggestTableView {
        let cell = tableView.dequeueReusableCellWithIdentifier("CustomTwo") as! CustomTwoTableViewCell
        cellToReturn = cell
    }

    return cellToReturn
}

I think this method maintains readability and clarity whilst also solving the error. I don't like having (dangerous) code written only for compatibility like return nil.

Tags:

Ios

Swift