Use of unresolved identifier - Swift 3

922 views Asked by At

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)
1

There are 1 answers

0
Jake On

I'm surprised your code even compiles since list is not in the same scope as your print command. The compiler should be catching that.

Essentially, the problem is that list is defined inside the do block. This means that the scope of list is limited to only the do block. Like @vadian said in his comment, execute print(list) after your guard statement and before the line containing } catch {. list will be in scope there and have the value of json?["response"] as? [[String : Any]] as long as that value is not nil (in which case the guard block will execute and return from the Dispatch.main.async block).

New code:

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 {
            print("list variable is nil")
            return
        }

        print(list)

        } catch {
            print("catch error...")
        }

     } //end of if let httpStatus

}//end dispacth

}//end of task

task.resume()

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:

DispatchQueue.global(attributes: .qosDefault).async {

}