About "Declaration is only valid at file scope"

Dennis picture Dennis · Feb 17, 2015 · Viewed 49.8k times · Source

I have a class+extension swift file. After adding a delegate that I declared in another file to the class, the Xcode shows "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)
    }

}

Answer

Nate Cook picture Nate Cook · Feb 17, 2015

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.