UITableView error when converting to Swift 3

85 Views Asked by At

Updating an old app from swift 2.2 to swift 4. I have to use swift 3 as a stepping stone. I converted to 3 but come across the following error:

Binary operator '==' cannot be applied to operands of type 'IndexPath' and 'Int`

The code is:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if (indexPath as NSIndexPath).row == 0 || indexPath == 1 {
        self.performSegue(withIdentifier: "NFL", sender: self)
    }

    if (indexPath as NSIndexPath).row == 1 {
        self.performSegue(withIdentifier: "AFL", sender: self)
    }

    if (indexPath as NSIndexPath).row == 2 {
        self.performSegue(withIdentifier: "FAI", sender: self)
    }

    if (indexPath as NSIndexPath).row == 3 {
        self.performSegue(withIdentifier: "IPA", sender: self)
    }
}

Why do I get this error in Swift 3 and not 2.2? I tried to force it into an "Int" but don't think I was going about it the right way.

2

There are 2 best solutions below

1
Gustavo Vollbrecht On BEST ANSWER

indexPath contains row and section

you need to specify if you want indexPath.row or indexPath.section

if you actually meant indexPath.row, your full code should look like:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if indexPath.row == 0 || indexPath.row == 1 {
            self.performSegue(withIdentifier: "NFL", sender: self)
        }


        if indexPath.row == 1 {
            self.performSegue(withIdentifier: "AFL", sender: self)
        }

        if indexPath.row == 2 {
            self.performSegue(withIdentifier: "FAI", sender: self)
        }

        if indexPath.row == 3 {
            self.performSegue(withIdentifier: "IPA", sender: self)
        }
}

Tips:

You don't need to cast to NSIndexPath

For this comparison purpose, you should use a switch statement instead of many ifstatements.

If indexPath.row == 1 it is going to performSegue twice with different results.

0
Omer Tekbiyik On

Beacause indexPath return IndexPath in Swift 4 and (indexPath as NSIndexPath).row returning Int so you can't force to equal .Also you don't even to use indexpath like indexPath as NSIndexPath. indexPath.row is enough