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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With