Ya3goobs
Ya3goobs

Reputation: 77

Using nested function

I am trying to use a nested function in xcode. What am I doing wrong?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "segue", sender: self)

        func prepare(for segue: UIStoryboardSegue, sender: Any?){
            print("Worked")
        }

    }

I am expecting my code to print "Worked" when the segue happens. It is not printing.

Upvotes: 0

Views: 42

Answers (1)

rmaddy
rmaddy

Reputation: 318774

The prepare method is a method of UIViewController. You need to properly override it. This means it can't be a nested function. It needs to be top-level method of your view controller.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "segue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("Worked")
}

If you need access to indexPath in prepare, you need to pass it, not self, as the sender parameter.

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

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("Worked")
    if let indexPath = sender as? IndexPath {
        // do stuff with indexPath
    }
}

Upvotes: 1

Related Questions