如何计算Swift中选定的UITableView行.indexPathForSelectedRow中的可选项

mig*_*ari 3 iphone xcode uitableview ios swift

我正在尝试获取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)
Run Code Online (Sandbox Code Playgroud)

一切都很好,直到选择了一些东西.但是当没有选定的行时,应用程序崩溃并出现"致命错误:在展开Optional值时意外发现nil".我认为这是因为选择是零,但如何使用Optionals编写此代码?我尝试了很多方法,但是当我取消选中所有选项时,app仍会崩溃.

Ron*_*ler 10

是的,你走在正确的轨道上.发生错误是因为没有选择任何行.像这样使用条件绑定:

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