-1

I called an API for rate currency, my variable "taux" is define at the begin of the class. So when I define the value of "taux" the value is great ( first print(taux)) but at the end ( last print(taux) ) the value of the variable is not the same, it's the old value of the variable. Just for information I checked the problem does not come from the for loop.

if let url = URL(string: "https://api.exchangeratesapi.io/latest?base=CAD") {
       URLSession.shared.dataTask(with: url) { data, response, error in
          if let data = data {
              do {
                let res = try JSONDecoder().decode(Currency.self, from: data)

                for rate in res.rates{

                    if rate.key == self.codeDevise{

                        self.taux = rate.value
                        print(self.taux)
                    }
                }

              } catch let error {
                 print(error)
              }
           }
       }.resume()
    }
    print(self.taux)
daaamiii
  • 1
  • 1

1 Answers1

0

Because you misunderstand how async code works. You create an URLSession DataTask, and call resume on it. When you set up the data task, you give it a completion handler to invoke AFTER THE NETWORK CALL HAS COMPLETED.

Your call to DataTask.resume returns immediately, before the data task has even sent the request out to the remote server. When the print statement in the last line of your code runs, the data task has not even started to execute, so that value from the network has not been installed into your instance variable.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • it's clearer now ! Do you have a suggestion to stock the value in the task and keep the value outside ? Thanks – daaamiii Jan 06 '20 at 01:16
  • Can you elaborate "to stock the value in the task and keep the value outside"? – Parth Jan 06 '20 at 02:56
  • I juste need to assign to my variable "taux" the result return by the API (rate.value) and use it after, but I don't know how I can do that – daaamiii Jan 06 '20 at 04:55