好吧,只是为了开始,继承我的代码:
import UIKit import ForecastIO class Weather { var temp: Float var condition: String var wind: Float var precip: Float init() { DarkSkyClient(apiKey: "<api key>").getForecast(latitude: Utils().getLat(),longitude: Utils().getLong()) { result in switch result { case .success(let currentForecast,_): self.temp = (currentForecast.currently?.temperature)! self.condition = (currentForecast.currently?.summary)! self.wind = (currentForecast.currently?.windSpeed)! self.precip = (currentForecast.currently?.precipitationProbability)! case .failure(let error): print(error) } } } }
所以我的错误出现了,因为我正在尝试初始化API调用内部的temp.我知道这不是最可靠的方式,但我试图让它首先发挥作用.
第一个错误是:
‘self’ captured by a closure before all members were initialized
在线DarkSkyClient(apiKey:“”).getForecast(纬度:Utils().getLat(),经度:Utils().getLong()){结果
我的第二个错误:
Return from initializer without initializing all stored properties
在倒数第二个}
现在,显然我没有正确初始化.我无法找到正确的方法来完成我的最终目标.也许我这样做完全错了?
我有可能猜到你遇到了并发问题.在对DarkSkyClient的异步调用返回之前,您可能正在尝试访问对象的属性(如果我错了,请提前道歉).即,事件的顺序是……
>初始化Weather对象,将temp设置为0
>调用DarkSkyClient开始,在后台运行
>读取临时变量 – 嘿,它是0!
>调用DarkSkyClient完成,将temp设置为您真正想要的值.坏
所以你真正需要做的是切换到控制模式的反转:
class Weather { var temp: Float var condition: String var wind: Float var precip: Float init(forecast: Forecast) { temp = (forecast.currently?.temperature)! condition = (forecast.currently?.summary)! wind = (forecast.currently?.windSpeed)! precip = (forecast.currently?.precipitationProbability)! } static func getWeather() { DarkSkyClient(apiKey: "<api key>").getForecast(latitude: Utils().getLat(),_): let weather = Weather(forecast: currentForecast) // Display the weather somewhere doSomethingWith(weather: weather) case .failure(let error): print(error) } } } }
如果您不熟悉使用异步API进行开发,那么阅读该主题是值得的.它可能非常棘手(遗憾的是,我没有任何关于良好引物的建议).希望这可以帮助!