Search code examples
swiftuicollectionviewlayoutnsindexpath

Conversion to Swift 2 NSIndexPath error


Problem: Upon converting to Swift 2 I get the following error: "Value of optional type [NSIndexPath]? not unwrapped, did you mean to use "!" or "?"". The issue is that if I use '?', it gives an error saying I should use '!', and if I use '!' it gives an error saying I should use '?'. Thus it creates this nasty little bug loop that seems to be unfixable.

Code:

override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {

    if identifier == Constants.SegueIdentifier {
        if let selectedRowIndex = collectionView?.indexPathsForSelectedItems().last as? NSIndexPath {
            if let cell = collectionView?.cellForItemAtIndexPath(selectedRowIndex) {
                //We check if the selected Card is the one in the middle to open the chat. If it's not, we scroll to the side card selected.
                if cell.frame.size.height > cell.bounds.size.height {
                    return true
                } else {
                    collectionView?.scrollToItemAtIndexPath(selectedRowIndex, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
                    return false
                }
            }
        }
    }

    return true
}

I haven't been able to come up with any work arounds since it seems like I need to somehow unwrap it. Has anyone seen this problem?


Solution

  • Solution:

    if let selectedRowIndex = collectionView!.indexPathsForSelectedItems()!.last! as? NSIndexPath
    

    My only concern is type safety but it works in my project as it currently is.