Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2.0 error Downcast from '[NSIndexPath]?' to '[indexpath]' only unwraps optional

Hi below code was working fine in swift1.2 but when I upgraded to swift 2.0:

func deselectAllRows() {
    if let selectedRows = tableView.indexPathsForSelectedRows as! [NSIndexPath] {
        for indexPath in selectedRows {
            tableView.deselectRowAtIndexPath(indexPath, animated: false)
        }
    }
}

It shows the following error :

Downcast from '[NSIndexPath]?' to '[indexpath]' only unwraps optional

Any clue on how to resolve this issue?

like image 871
Zya Zyanga Avatar asked Jan 17 '26 03:01

Zya Zyanga


2 Answers

You don't have to force a typecast anymore, indexPathsForSelectedRows returns the right type:

func deselectAllRows() {
    if let selectedRows = tableView.indexPathsForSelectedRows {
        for indexPath in selectedRows {
            tableView.deselectRowAtIndexPath(indexPath, animated: false)
        }
    }
}
like image 55
Eric Aya Avatar answered Jan 19 '26 18:01

Eric Aya


The tableView.indexPathsForSelectedRows returns [NSIndexPath]?, so you don't need to type cast it. You can just write it like:

func deselectAllRows()
{
   if let selectedRows = tableView.indexPathsForSelectedRows
   {
      for indexPath in selectedRows
       {
           tableView.deselectRowAtIndexPath(indexPath, animated: false)
        }
   }
}
like image 26
Midhun MP Avatar answered Jan 19 '26 18:01

Midhun MP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!