首页 > 解决方案 > 声明仅在文件范围错误时有效

问题描述

任何人都可以向我解释为什么扩展以这种方式工作。

我为我的主 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 {
}

我不把扩展名放在课堂上

标签: iosswiftxcode

解决方案


问题是 - 为什么将扩展名放在 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
}

推荐阅读