Swift || Returning a class that can be used by other methods from an API call

半腔热情 提交于 2019-12-02 12:22:41

What you have not understood is that the completion handler in your GET call is every bit as asynchronous as the original Weather API call. Thus you cannot run any code after it that depends on what's in it. The order of events is as follows:

// 1
Weather.Get(lat:"32.9005", long:"-96.7869", completionHandler: {currentWeather in
    if let testWeather = currentWeather{ // 3!!!
        print(testWeather.city) // 4!!!!!!
        print("completionHandler")
    }
})
print(testWeather.city) // 2

Moreover, what is the testWeather in the last line? Is it a property, self.testWeather? It would need to be. But even if it is, you have neglected to give self.testWeather a value; the if let testWeather is a different testWeather (it is local to the completion handler only and cannot "leak" out of it). However, even if you had done that, it still wouldn't work, because the code would still run in the wrong order:

// 1
Weather.Get(lat:"32.9005", long:"-96.7869", completionHandler: {currentWeather in
    if let testWeather = currentWeather{ // 3
        print(testWeather.city) // 4
        print("completionHandler") 
        self.testWeather = testWeather // 5; better but it won't help the _next_ print
    }
})
print(testWeather.city) // 2

Still, remembering to write to self.testWeather (5) would at least allow other code to access this value, provided it runs later.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!