Minhal Khan Minhal Khan - 6 months ago 138
Swift Question

NSIndexPath can never be nil, comparison isn't allowed

Im trying to see if the user presses a cell in a table view, but i cannot compare it to nil? How would i check if a cell has not been pressed? This is the handler when the user does a long press on the table view

func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
let p: CGPoint = gestureRecognizer.locationInView(self.tableView)
let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(p)!
if indexPath == nil{

}
else if gestureRecognizer.state == .Began {
print(indexPath.row)
}

}

Answer

You should not force unwrap and then check for nil - that would crash your app. What you should do is: drop the unwrap and then compare!

func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
    let point = gestureRecognizer.locationInView(self.tableView)
    let indexPath = self.tableView.indexPathForRowAtPoint(point)
    if let touchedPath = indexPath {
        if gestureRecognizer.state == .Began {
            print(touchedPath.row)
        }
    }
}