title: Modify Global Variable Inside Closure (Swift 4)
body: <p>I am trying to modify the global variable currentWeather (of type CurrentWeather) using this function, which is meant to update said variable with the information retrieved from the URL and return a bool signifying its success. However, the function is returning false, as currentWeather is still nil. I recognize that the dataTask is asynchronous, and that the task is running in the background parallel to the application, but I don't understand what this means for what I'm trying to accomplish. I also am unable to update currentWeather after the do block, as weather is no longer recognized after exiting the block. I did try using "self.currentWeather", but was told it was an unresolved identifier (perhaps because the function is also global, and there is no "self"?). </p>
  
  <p>The URL is not currently valid because I took out my API key, but it is working as expected otherwise, and my CurrentWeather struct is Decodable. Printing currentWeatherUnwrapped is also consistently successful. </p>
  
  <p>I did look around Stack Overflow and through Apple's official documentation and was unable to find something that answered my question, but perhaps I wasn't thorough enough. I'm sorry if this is a duplicate question. Direction to any further relevant reading is also appreciated! I apologize for the lack of conformity to best coding practices - I'm not very experienced at this point. Thank you all so much! </p>
  
  <pre><code>func getCurrentWeather () -&gt; Bool {
  let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/\(state)/\(city).json"
  
  guard let url = URL(string: jsonUrlString) else { return false }
  
  URLSession.shared.dataTask(with: url) { (data, response, err) in
      // check error/response
  
      guard let data = data else { return }
  
      do {
          let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
          currentWeather = weather
          if let currentWeatherUnwrapped = currentWeather {
              print(currentWeatherUnwrapped)
          }
      } catch let jsonErr {
          print("Error serializing JSON: ", jsonErr)
      }
  
      // cannot update currentWeather here, as weather is local to do block
  
      }.resume()
  
  return currentWeather != nil
  }
  </code></pre>