John Harding John Harding - 2 months ago 5
Swift Question

Missing return in a function expected to return 'UITableViewCell', but actually returning twice

I am trying to set up a table view that will change cells based on the segmented controller at the top. However, in attempting to change the cells when reloading the tableview, I am receiving a return function error when in fact I have a return function. What can I do to fix this?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {




if friendSelector.selectedSegmentIndex == 0 {
print("0")

cell = self.friendsTable.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FriendsTableViewCell


cell.nameLabel.text = friends[indexPath.row]
cell.bacLabel.text = String(friendsBac[indexPath.row])
cell.statusImageView.image = friendsImage[indexPath.row]

return cell

}

if friendSelector.selectedSegmentIndex == 1 {
print("1")

celladd = self.friendsTable.dequeueReusableCell(withIdentifier: "celladd", for: indexPath) as! FriendsAddTableViewCell

celladd.nameLabel.text = requested[indexPath.row]
celladd.statusImageView.image = UIImage(named: "greenlight")

return celladd


}

}


View of the Table With Two different Custom UITableViewCells

Answer

You should return a cell. In the above code, if both conditions failed, then nothing will be returned. So a warning raised. Just remove second "if" condition and use else case as follows:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if friendSelector.selectedSegmentIndex == 0 {
        print("0")

        cell = self.friendsTable.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FriendsTableViewCell


        cell.nameLabel.text = friends[indexPath.row]
        cell.bacLabel.text = String(friendsBac[indexPath.row])
        cell.statusImageView.image = friendsImage[indexPath.row]

        return cell

    }

    else {
        print("1")

        celladd = self.friendsTable.dequeueReusableCell(withIdentifier: "celladd", for: indexPath) as! FriendsAddTableViewCell

        celladd.nameLabel.text = requested[indexPath.row]
        celladd.statusImageView.image = UIImage(named: "greenlight")

        return celladd


    }

}