Hunter
Hunter

Reputation: 421

Is there a shorter way to use indexPath.row?

Is there a shorter way to use indexPath.row? I am currently using this right now:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    if indexPath.row == 0 {

        self.performSegueWithIdentifier("0", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    } else if indexPath.row == 1 {

        self.performSegueWithIdentifier("1", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    } else if indexPath.row == 2 {

        self.performSegueWithIdentifier("2", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    } else if indexPath.row == 3 {

        self.performSegueWithIdentifier("3", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    } else if indexPath.row == 4 {

        self.performSegueWithIdentifier("4", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    } else if indexPath.row == 5 {

        self.performSegueWithIdentifier("5", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    } else if indexPath.row == 6 {

        self.performSegueWithIdentifier("6", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    } else if indexPath.row == 7 {

        self.performSegueWithIdentifier("7", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    } else if indexPath.row == 8 {

        self.performSegueWithIdentifier("8", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    } else if indexPath.row == 9 {

        self.performSegueWithIdentifier("9", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    } else if indexPath.row == 10 {

        self.performSegueWithIdentifier("10", sender: self)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    }
}

I'm actually using 42 statements of indexPath.row in my project but I only put 11 above as an example.

Upvotes: 0

Views: 258

Answers (1)

Rashwan L
Rashwan L

Reputation: 38843

You could just do it like this

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.performSegueWithIdentifier(String(indexPath.row), sender: self)
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
}

Upvotes: 1

Related Questions