I have a problem with the following code in Swift3. I am not sure what I am doing wrong but when I try to print 'list' I receive a compiler error 'Use of unresolved identifier'. Can anybody point me the right direction?
let task = URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async {
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]
guard let list = json?["response"] as? [[String : Any]] else {
return
}
} catch {
print("catch error...")
}
} //end of if let httpStatus
}//end dispacth
}//end of task
task.resume()
print(list)
I'm surprised your code even compiles since
listis not in the same scope as yourprintcommand. The compiler should be catching that.Essentially, the problem is that
listis defined inside thedoblock. This means that the scope oflistis limited to only thedoblock. Like @vadian said in his comment, executeprint(list)after yourguardstatement and before the line containing} catch {.listwill be in scope there and have the value ofjson?["response"] as? [[String : Any]]as long as that value is notnil(in which case theguardblock will execute and return from theDispatch.main.asyncblock).New code:
Also, note that since you're not doing any UI updates (at least yet) here, you do not need to execute this code on the main thread. You could use this instead: