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
list
is not in the same scope as yourprint
command. The compiler should be catching that.Essentially, the problem is that
list
is defined inside thedo
block. This means that the scope oflist
is limited to only thedo
block. Like @vadian said in his comment, executeprint(list)
after yourguard
statement and before the line containing} catch {
.list
will be in scope there and have the value ofjson?["response"] as? [[String : Any]]
as long as that value is notnil
(in which case theguard
block will execute and return from theDispatch.main.async
block).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: