I have a segue from a table view controller to another view controller. Inside the method prepare(for: sender) I need to get the indexPath of the cell that triggered the segue. Is it Ok to force unwrap the index path in this case? After all the prepare() method was triggered by tapping on a table row so it seems I can make the assumption that ‘sender’ contains a reference to a valid object yes?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "TheCorrectSegue" {
let indexPath = tableView.indexPath(for: sender as! UITableViewCell)! <-- is this OK?
}
@mchartier. Thanks very much for your question! Here is a solution that might help you:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == “TheCorrectSegue”, let cell = sender as? UITableViewCell {
let indexPath = tableView.indexPath(for: cell)!
}
or to get rid of the force unwrapping entirely:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if
segue.identifier == “TheCorrectSegue”,
let cell = sender as? UITableViewCell,
let indexPath = tableView.indexPath(for: cell)
{
//do whatever you need to do with your indexPath here
}
}