Reputation: 4516
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)
}
Upvotes: 0
Views: 685
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