How to count selected UITableView rows in Swift. Optional in indexPathForSelectedRow
ios, iphone, swift, uitableview, xcode
Solution
Yes, you're on the right track. The error is happening because no rows are selected. Use conditional binding like so:
func updateCount(){
if let list = tableView.indexPathsForSelectedRows() as? [NSIndexPath] {
println(list.count)
}
}
Problem
I'm trying to get number of selected rows in my tableView: ``` self.tableView.setEditing(true, animated: true) tableView.allowsMultipleSelection = true func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { updateCount() } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { updateCount() } func updateCount(){ let list = tableView.indexPathsForSelectedRows() as [NSIndexPath] println(list.count) ``` Everything works good until something is selected. But when there is no selected row, app crashes with "fatal error: unexpectedly found nil while unwrapping an Optional value". I think it is because selection is nil, but how to write this code with Optionals? I tried many ways but app still crashes when I uncheck all selection.