Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About "Declaration is only valid at file scope"

I have a class and extension Swift file. After adding a delegate that I declared in another file to the class, Xcode shows this error

Declaration is only valid at file scope

at the extension line. I don't know what the problem is.

Can anyone help me to fix it?

class ListViewController: UIViewController, AddItemViewControllerDelegate {...}

extension ListViewController: UITableViewDataSource{
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        performSegueWithIdentifier("ShowDetail", sender: indexPath)
    }

}
like image 524
Dennis Avatar asked Feb 17 '15 03:02

Dennis


4 Answers

The error is somewhere in your ... — that error means that your ListViewController class didn't get closed, so the extension is being interpreted as nested inside, like this:

class ListViewController {
    ...
    extension ListViewController {
    }
}

Find the missing closing brace and you should solve the problem.

like image 158
Nate Cook Avatar answered Nov 12 '22 19:11

Nate Cook


The extension must be at the root level - don't embed them into a class or whatever.

like image 21
Jordan Avatar answered Nov 12 '22 18:11

Jordan


Make sure that the extension is declared at the end of your main class and after the last curly braces "}"

class ListViewController: UIViewController, AddItemViewControllerDelegate {
   //Make sure that everything is clean here! 
}

extension ListViewController: UITableViewDataSource{
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        performSegueWithIdentifier("ShowDetail", sender: indexPath)
    }
}
like image 16
polarware Avatar answered Nov 12 '22 18:11

polarware


Make sure your class and extension are seperated.

class ViewController: UIViewController {}

extension name: type {}
like image 4
Siddharth Prothia Avatar answered Nov 12 '22 20:11

Siddharth Prothia