0

I'm having trouble working out why the following function isn't returning:

func getCurrentWeather(cityID: Int) -> Weather? {
    let cityIDAsString = String(cityID)
    guard let url = getCityWeatherURL(from: cityIDAsString) else { return nil }
    var weather: Weather?

    self.data(url: url, sucess: { (data) in
        weather = self.convertDataToWeather(data: data)
        print(weather)
    }) { (error) in
        print(#function, error)
    }
    print(weather)
    return weather
}

(I've not posted getCityWeatherURL as that's working when printing it's value).

When I print weather the first time, it's correct and not nil so I know my other functions are working correctly. But when I later try to return the value of weather, it returns nil.

The other relevant function is this I think:

private func data(url: URL, sucess: @escaping (Data) -> Void, failure: @escaping (Error) -> Void) {
    let task = URLSession.shared.dataTask(with: url) { (data, _, error) in
        if let error = error {
            failure(error)
        } else if let data = data {
            sucess(data)
        }
    }
    task.resume()
}

If anyone is able to spot my problem I'd really appreciate it! (Notes on my general code are welcome too!)

ADB
  • 591
  • 7
  • 21

0 Answers0