I would like to set the return value equal to the value in my for loop so that I can return it from the func. Do you have an idea how to do that?
static func getStones() -> Double {
let url = NSURL(string: "MYURL")
let request = NSMutableURLRequest(url: url as URL!)
var stonesNew = Double()
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
let contacts = responseString["Sheet1"] as? [AnyObject]
for contact in contacts!{
let stones = contact["stones"] as! Double
stonesNew = stones
}
}
task.resume()
return stonesNew
}
- So I would like to set "stonesNew" to my downloaded "stones" but it always returns stones = 0
task.resume()starts off the task and then returns. So when it finishes and you are returningstonesNew, the task has not yet completed. If you must do it this way, you need to use a semaphore to wait for the result to be returned from the server. A better approach would be to pass a handler to this function to call when the result is returned.