Search code examples
iosswiftnsindexpath

Cannot convert value of type 'NSIndexPath' to expected argument type 'NSIndexPath'


Cannot convert value of type 'NSIndexPath' to expected argument type 'NSIndexPath'

Error is on self.collectionView?.moveItemAtIndexPath(obj[0] as! NSIndexPath, toIndexPath: obj[1] as! NSIndexPath) line

if let changes = self.objectChanges{
    self.collectionView?.performBatchUpdates({ () -> Void in
        for change in changes as NSArray as! [NSDictionary] {
            change.enumerateKeysAndObjectsUsingBlock { (keyObject:AnyObject!, obj:AnyObject!, stop) -> Void in
                let key = keyObject as! NSNumber
                let type = NSFetchedResultsChangeType(rawValue: key.unsignedLongValue)!
                switch (type)
                {
                    case .Insert:
                        self.collectionView?.insertItemsAtIndexPaths(obj as! ([NSIndexPath]))
                    case .Delete:
                        self.collectionView?.deleteItemsAtIndexPaths(obj as! ([NSIndexPath]))
                    case .Update:
                        self.collectionView?.reloadItemsAtIndexPaths(obj as! ([NSIndexPath]))
                    case .Move:
                        self.collectionView?.moveItemAtIndexPath(obj[0] as! NSIndexPath, toIndexPath: obj[1] as! NSIndexPath)
                    default:
                        break
                }
            }
        }
    }, completion: nil)
}

Solution

  • You are trying to apply subscript to obj which is AnyObject not Array. You should cast obj to [NSIndexPath]:

    if let obj = obj as? [NSIndexPath] {
        switch (type) {
            case .Insert:
                self.collectionView?.insertItemsAtIndexPaths(obj)
            case .Delete:
                self.collectionView?.deleteItemsAtIndexPaths(obj)
            case .Update:
                self.collectionView?.reloadItemsAtIndexPaths(obj)
            case .Move:
                self.collectionView?.moveItemAtIndexPath(obj[0], toIndexPath: obj[1])
            default:
                break
        }
    }