ios 关于“声明仅在文件范围内有效”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28554231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
About "Declaration is only valid at file scope"
提问by Dennis
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.
我有一个类+扩展 swift 文件。将我在另一个文件中声明的委托添加到类后,Xcode 在扩展行显示“声明仅在文件范围内有效”。我不知道是什么问题。
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)
}
}
回答by Nate Cook
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:
错误在您的某处...
- 该错误意味着您的ListViewController
类没有关闭,因此扩展名被解释为嵌套在内部,如下所示:
class ListViewController {
...
extension ListViewController {
}
}
Find the missing closing brace and you should solve the problem.
找到缺少的右括号,您应该可以解决问题。
回答by Jordan
The extension must be at the root level - don't embed them into a class or whatever.
扩展必须在根级别 - 不要将它们嵌入到类或其他任何东西中。
回答by polarware
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)
}
}
回答by Siddharth Prothia
Make sure your class and extension are seperated.
确保你的类和扩展是分开的。
class ViewController: UIViewController {}
extension name: type {}
回答by John Markham
I had my extension calls at the bottom of my file and put them at the top and that fixed it for me. At the bottom, they were outside the class scope so I was a little stumped and just tried this.
我在我的文件底部有我的扩展调用并将它们放在顶部并为我修复了它。在底部,它们在课堂范围之外,所以我有点难住,只是尝试了这个。