ios - 声明仅在文件范围错误时有效
问题描述
任何人都可以向我解释为什么扩展以这种方式工作。
我为我的主 ViewController 编写了一个扩展,其中包括一个函数:
extension WeatherMainScreen {
func load(lat: Double, long: Double){
service.getWeatherInfo(lat: lat, long: long) { [weak self] temp in
self?.tempNumber.text = "\(temp.currently.temperature)"
self?.results = temp.daily.data
self?.tableView.reloadData()
}
}
}
问题是,如果我将此扩展名放在 ViewController 类下,则会收到错误消息“声明仅在文件范围内有效”。但如果我把它放在上面它工作正常。
奇怪的部分(对我来说)是在这个特定的项目中,我的 ViewController 类有点大,但是如果我在一个不同的项目中尝试这个扩展,它有更小的 ViewController 类并将扩展放在它下面,一切正常,没有错误。
问题是 - 为什么将扩展名放在 VC 类上方有效,但如果我放在 VC 类下,它会显示此“声明仅在文件范围内有效”错误?
更多解释
这样它就不能显示声明错误:
class WeatherMainScreen: UIViewController {
}
extension WeatherMainScreen {
// your code
}
这样它的工作原理:
extension WeatherMainScreen {
// your code
}
class WeatherMainScreen: UIViewController {
}
我不把扩展名放在课堂上
解决方案
问题是 - 为什么将扩展名放在 VC 类上方有效,但如果我放在 VC 类下,它会显示此“声明仅在文件范围内有效”错误?
答:扩展应该在根级别,而不是在任何类中。
这是错误的。由于扩展嵌套在WeatherMainScreen
class WeatherMainScreen: UIViewController {
extension WeatherMainScreen { // wrong as its declared inside the WeatherMainScreen
// your code
}
}
这是正确的,因为扩展是在根级别声明的
class WeatherMainScreen: UIViewController {
}
extension WeatherMainScreen { // correct way.
// your code
}
推荐阅读
- python - python嵌套for循环通过第一个循环添加增量值
- javascript - 未找到模块:错误:您尝试导入位于项目 src/ 目录之外的 babel-preset
- python - 新值被复制到整列
- python - 检查 CSV 数据中的整数,然后删除该整数
- r - step_BoxCox() 带负数据
- c# - 我可以在 2 个不同的会话中调试 MVC 5 应用程序吗?
- spring - 弹簧延迟响应和路由器功能
- excel - Excel:是否可以在一页上运行两列列表并将其转移到辅助选项卡?
- python - 使用 Python 基于参考树合并列表项
- pyspark - 将多个 avro 文件与不兼容的模式结合起来