Onichan
Onichan

Reputation: 4516

Removing Value from Array when Deselect Cell

I'm trying to remove a particular item in the array selectedFoodTypes if a user deselects a row. However, I keep running into the error:

fatal error: unexpectedly found nil while unwrapping an Optional value

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let indexPath = tableView.indexPathForSelectedRow();
    let deselectedCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
    selectedFoodTypes = selectedFoodTypes.filter {$0 != deselectedCell.textLabel!.text!}
    println(selectedFoodTypes)
}

enter image description here

Upvotes: 0

Views: 685

Answers (1)

rakeshbs
rakeshbs

Reputation: 24572

Why are you calling let indexPath = tableView.indexPathForSelectedRow()

The indexPath parameter of the function gives you the indexPath of the deselected row.

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let deselectedCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
    selectedFoodTypes = selectedFoodTypes.filter {$0 != deselectedCell.textLabel!.text!}
    println(selectedFoodTypes)
}

The above code might work. But comparing with textLabel.text of the cell is not a good idea. If datasourceArray is an array for example and set as the tableView dataSource, you can do

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let deselectedCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
    selectedFoodTypes = selectedFoodTypes.filter {$0 != datasourceArray[indexPath.row]}
    println(selectedFoodTypes)
}

Upvotes: 1

Related Questions