How to count selected rows of UITableView in Swift. Optional in indexPathForSelectedRow

I am trying to get the number of selected rows in a 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 well until something is selected. But when there is no row selected, the application crashes with "fatal error: Null encountered unexpectedly while expanding optional value". I think this is because the selection is null, but how do I write this code using Optionals? I've tried many ways, but the app still crashes when I deselect all.

+3


source to share


2 answers


Yes, you are on the right track. The error occurs because no row is selected. Use conditional binding like this:



func updateCount(){        
    if let list = tableView.indexPathsForSelectedRows() as? [NSIndexPath] {
        println(list.count)
    }
}

      

+10


source


You can just do



func updateCount(){
   if let list = tableView.indexPathsForSelectedRows {
        print(list.count)
   }
 }

      

+2


source







All Articles