-1

I have a method like this:

internal func handlePan(_ sender: UIPanGestureRecognizer) {
    if (sender.state == .began) {
        let initialPanPoint = sender.location(in: collectionView)
        findDraggingCellByCoordinate(initialPanPoint)
    } else if (sender.state == .changed) {
        let newCenter = sender.translation(in: collectionView!)
        updateCenterPositionOfDraggingCell(newCenter)
    } else {
        if let indexPath = draggedCellPath {
           // finishedDragging(collectionView!.cellForItem(at: indexPath)!)
            finishedDragging((collectionView?.cellForItem(at: indexPath))!)
        }
    }
}

And I am getting a crash on

finishedDragging((collectionView?.cellForItem(at: indexPath))!)

fatal error: unexpectedly found nil while unwrapping an Optional value

How can I unwrap this? Please help me. Thanks.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
user1960169
  • 3,533
  • 12
  • 39
  • 61
  • Duplicate of every other "unexpectedly found nil" question (and there are thousands of them). `!` means crash. – matt Jul 30 '17 at 18:06

1 Answers1

0

Currently, you're force unwrapping an optional which happens to be nil. Therefore, you need to add an additional clause to thee optional unwrapping of indexPath to determine if the collection view can return a cell at that index path. If the collection view cannot return a cell at index path, it will return nil and the condition will not be executed.

if let indexPath = draggedCellPath, let cell = collectionView?.cellForItem(at: indexPath){
  finishedDragging(cell)
}
Josh Hamet
  • 957
  • 8
  • 10