【问题标题】:How to unwrap the optional value [duplicate]如何解开可选值[重复]
【发布时间】:2017-07-30 17:53:57
【问题描述】:

我有这样的方法:

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

致命错误:在展开可选值时意外发现 nil

我怎样才能解开这个? 请帮我。 谢谢。

【问题讨论】:

  • 所有其他“意外发现 nil”问题的重复(并且有数千个)。 ! 表示崩溃。

标签: ios swift3 unwrap


【解决方案1】:

目前,您正在强制解开一个恰好为 nil 的可选项。因此,您需要在 indexPath 的可选展开中添加一个附加子句,以确定集合视图是否可以返回该索引路径处的单元格。如果collection view不能返回index path处的cell,则返回nil,条件不会被执行。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多