Cannot tune value of type '[NSIndexPath]' with type Int

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

Cannot adjust value of type '[NSIndexPath]?' with type 'Int'

for the following code code:

let indexPath = indexPaths[0] as! NSIndexPath 

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

Here is the complete prepareForSegue method. I'm not sure if this is a Swift 2 bug, 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 } } 
+5
source share
3 answers

In the iOS8 SDK, indexPathsForSelectedItems indexPathsForSelectedItems declared as:

 func indexPathsForSelectedItems() -> [AnyObject] // returns nil or an array of selected index paths 

This was a bug in the SDK because indexPathsForSelectedItems() returns nil when there are no items selected.

In the iOS9 SDK, which is declared as:

 public func indexPathsForSelectedItems() -> [NSIndexPath]? 

2 differences here

  • The error has been fixed and returns Optional
  • returns an NSIndexPath array instead of AnyObject , since Objective-C supports simple Generics.

So,

  • You need to deploy it.
  • You do not need to point them to NSIndexPath

Try:

  let indexPaths = self.collectionView.indexPathsForSelectedItems()! let indexPath = indexPaths[0] 
+1
source

You must expand the array first and then use it for this code to work:

 let indexPath = indexPaths?[0] as! NSIndexPath 

By the way, do not use! to expand variables that have a chance to become zero, or your final application will encounter a crash at runtime.

+2
source

You need to expand the array, but instead of forcing it to unzip! it might be safer to use if you want you to not deploy zero

 if let indexPaths = self.collectionView.indexPathsForSelectedItems() where indexPaths.count > 0{ let indexPath = indexPaths[0] } 
0
source

All Articles