如何解包可选值

How to unwrap the optional value

我有这样的方法:

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))!)
        }
    }
}

我在

上遇到了崩溃
finishedDragging((collectionView?.cellForItem(at: indexPath))!)

fatal error: unexpectedly found nil while unwrapping an Optional value

我该如何打开它? 请帮我。 谢谢

目前,您正在强制展开一个恰好为 nil 的可选项。因此,您需要向 indexPath 的可选展开添加一个附加子句,以确定集合视图是否可以 return 该索引路径处的单元格。如果集合视图不能 return 索引路径中的单元格,它将 return nil 并且不会执行条件。

if let indexPath = draggedCellPath, let cell = collectionView?.cellForItem(at: indexPath){
  finishedDragging(cell)
}