0

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.

2
  • Why are you trying to use a nested function? Commented Sep 6, 2019 at 22:36
  • Because I want to get the "indexPath.row" from the didSelectRowAt and use it in the prepare function. Commented Sep 6, 2019 at 22:38

1 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The problem is I need to get the array data from the tableview and use it in the prepare function. How would I do that without nesting them, because I cant create a variable in the didSelectRowAt function and use it in the prepare function.
Your array is a property of the class, right? Access it like you are probably doing in several of your other existing methods of your class. If you need the indexPath, pass that as the sender, not self.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.