简体   繁体   English

在等待属性初始化的 init 中调用函数

[英]Call Function in init that waits for properties to initialise

I have an Observable Object class to store a forecast object for my app我有一个 Observable Object 类来存储我的应用程序的预测对象

The class looks like this:这个类看起来像这样:

final class ForecastData: ObservableObject {
    @Published var forecast: DarkSkyResponse

    public func getForecast(at location: CLLocation) {
        let request = DarkSkyRequest(key: "KEYGOESHERE")
        let point = DarkSkyRequest.Point(location.coordinate.latitude, location.coordinate.longitude)

        guard let url = request.buildURL(point: point) else {
            //Handle this better
            preconditionFailure("Failed to construct URL")
        }

        let task = URLSession.shared.dataTask(with: url) {
            data, response, error in

            DispatchQueue.main.async {
                guard let data = data else {
                    //Handle this better
                    fatalError("No Data Recieved")
                }
                guard let forecast = DarkSkyResponse(data: data) else {
                    //Handle this better
                    fatalError("Decoding Failed")
                }
                self.forecast = forecast
            }
        }
        task.resume()
    }

    init() {
        self.getForecast(at: CLLocation(latitude: 37.334987, longitude: -122.009066))
    }
}

The first part simply generates a URL to access the API by.第一部分只是生成一个 URL 来访问 API。 Then I start a URLSession which downloads the data and then parses it into a DarkSkyResponse object.然后我启动一个URLSession ,它下载数据,然后将其解析为一个DarkSkyResponse对象。 Finally I set the @Published variable to the forecast object.最后我将@Published变量设置为预测对象。

My problem is when I call the function in the initialiser, I get an error because the forecast property is not initialised.我的问题是当我在初始化程序中调用该函数时,我收到一个错误,因为预测属性未初始化。 What is the best way to get around this?解决这个问题的最佳方法是什么? Where should I call the function?我应该在哪里调用函数? By the way I am using this class in my SwiftUI View using an @ObservedObject property wrapper顺便说一句,我在我的 SwiftUI 视图中使用这个类使用@ObservedObject属性包装器

Case1: use optional (and you need to handle it in View) Case1:使用optional(需要在View中处理)

@Published var forecast: DarkSkyResponse?

Case2: use some default instance案例2:使用一些默认实例

@Published var forecast = DarkSkyResponse()

Both variants are equivalent and acceptable, so just by your preference.两种变体都是等效且可接受的,因此仅凭您的喜好即可。

Try this changes:试试这个改变:

@Published var forecast: DarkSkyResponse!

and

init() {
    super.init()
    self.getForecast(at: CLLocation(latitude: 37.334987, longitude: -122.009066))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM