Search code examples
iosswiftsegueunwind-segue

Stuck with "Type of expression is ambiguous without more context" in prepare function


I'm new to coding Swift, so please excuse me if this error is a simple answer.. I am trying to transfer data to another viewcontroller, but struggling with "Type of expression is ambiguous without more context" error.

I made a @IBoutlet var mainTableView inside of the Viewcontroller right now.

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let indexPath = mainTableView.indexPathForSelectedRow {
            habitSelected = habitlist[indexPath.row]
        }

Here's full code I made

https://i.sstatic.net/8mS4F.png

https://i.sstatic.net/Mzgwf.png


Solution

  • A alternative way to do that is to pass the row in the sender parameter

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "unwindTableViewControiler", sender: indexPath.row)
    }
    

    and it's recommended to check the identifier of the segue before unwrapping the sender

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "unwindTableViewControiler" {
            let row = sender as! Int
            habitSelected = habitlist[row]
        }
    }