转换为Swift 2 NSIndexPath错误

时间:2016-01-12 19:38:28

标签: swift uicollectionviewlayout nsindexpath

问题:转换为Swift 2后,我收到以下错误:“可选类型[NSIndexPath]的值?未解包,是不是要使用”!“或”?“”。问题是,如果我使用'?',它会出错,说我应该使用'!',如果我使用'!'它给出了一个错误,说我应该使用'?'。因此,它创建了这个令人讨厌的小bug循环,似乎是不可修复的。

代码:

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
}

我无法想出任何工作,因为我似乎需要以某种方式解开它。有没有人见过这个问题?

2 个答案:

答案 0 :(得分:0)

json.dumps返回indexPathsForSelectedItems()(可选),您必须为可选链接添加另一个问号,并删除[NSIndexPath]?,因为编译器知道展开的类型。

as? NSIndexPath

答案 1 :(得分:0)

解决方案:

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

我唯一关心的是类型安全,但它在我目前的项目中有效。