-4

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.

1
  • 3
    The phrase indexPath == 1 wouldn't have compiled in Swift 2.2 either, so you are not really telling us the truth here.
    – matt
    Commented Feb 20, 2019 at 21:48

2 Answers 2

2

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.

1
  • 1
    The logic in this answer (and probably the original code) has a big flaw. The 2nd if will result in two segues being performed if row is 1. And the use of if else would be better here.
    – rmaddy
    Commented Feb 20, 2019 at 21:59
1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.