Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot subscript a value of type '[NSIndexPath]' with a type Int

So I'm currently converting a project to Swift 2 using Xcode 7 beta, and I am currently getting the error:

Cannot subscript a value of type '[NSIndexPath]?' with a type 'Int'

for the following ling of code:

let indexPath = indexPaths[0] as! NSIndexPath

when trying to pass data to a view controller when a user selects a cell in the UICollectionView using prepareForSegue method.

Here is the complete prepareForSegue method. I am unsure if this is a Swift 2 error, but it works fine when using Swift 1.1 for iOS 8.4.

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "details" {
    let vc = segue.destinationViewController as! DetailsViewController

    let indexPaths = self.collectionView.indexPathsForSelectedItems()
    let indexPath = indexPaths[0] as! NSIndexPath

    let selectedItem = items[indexPath.row]

    vc.selectedItem = selectedItem

    }
}
like image 747
RileyDev Avatar asked Oct 20 '22 03:10

RileyDev


1 Answers

First you should unwrap array then use it so this code should work:

let indexPath = indexPaths?[0] as! NSIndexPath

By the way, avoid using ! to unwrap variables that have chance to be nil or your final app will face runtime crash.

like image 152
Mousavian Avatar answered Oct 21 '22 15:10

Mousavian