David David - 3 months ago 6
Swift Question

Swift error: Value of type 'NSObject - > () 'AnimalListTableViewController' has no member 'tableView'

I'm trying to get rid of these errors in swift xcode

Value of type 'NSObject -> () -> AnimalListTableViewController' has no member 'tableView' / Consecutive declarations on a line must be separated by ';' / Variable used within its own initial value

If screenshot is too small, here is the code

import UIKit

class AnimalListTableViewController: UITableViewController
{
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
let indexPath = self.tableView.indexPathForSelectedRow()//this is where the error appears, it says Value of type 'NSObject -> () -> AnimalListTableViewController' has no member 'tableView'
override func prepareForSegue(segue: UIStoryboardSegue,
sender: AnyObject?)
{
if let DetailViewController =
segue.destinationViewController
as? DetailViewController {
}
}

if let indexPath = self.tableView.indexPathForSelectedRow()
{
DetailViewController.Animal = animals[indexPath.row]
}
}

Answer

The code is malformed.

At the line generating the error, you're working within the context of the AnimalListTableViewController class declaration, not within a function. When reading it left-to-right, it's as if you are trying to declare a constant data member indexPath of the AnimalListTableViewController class.

It looks like you're trying to do this:

class AnimalListTableViewController: UITableViewController
{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }

    override func prepareForSegue(segue: UIStoryboardSegue,
        sender: AnyObject?)
    {
        if let detailViewController = segue.destinationViewController as? DetailViewController, let indexPath = self.tableView.indexPathForSelectedRow {
            detailViewController.Animal = animals[indexPath.row]
        }
    }
}

Cleaned up some other things too:

  • don't use the class name (DetailViewController) also as the variable name. Changed it to detailViewController.
  • collapsed the if let statements into a single statement. Cleaner; avoids optionals.