T
T
tupoi2017-05-11 21:53:05
Swift
tupoi, 2017-05-11 21:53:05

Why doesn't Xcode see the variable?

Good day, there is such a problem, I make a request to the server, I get a response in the form of JSON, I parse JSON and save it all to a variable

Alamofire.request("http://127.0.0.1:8000/api/auditOS/", method: .get).responseJSON { response in
            let jsonParse = JSON(response.result.value!)
            print(jsonParse)
        }

But then this variable must be used, and XCode says that such a variable does not exist, what should I do? I tried to contact through self - it does not help, he sees it only within curly braces with an Alamofire request, outside of them immediately throws an error. I would be grateful for the answer why this is happening and how to solve this problem)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Skyrocker33, 2017-05-13
@tupoi

Judging by what you wrote, the answer is extremely simple: you declare a jsonParse constant inside a closure. You can see it inside the closure. This problem can be solved by declaring a variable (var instead of let) outside of functions.

B
Buick, 2017-05-11
@Buick

Because here is an asynchronous model and this variable can only be used in callback, where you have print.
Roughly speaking, this callback will (most likely) be executed in another thread, in parallel with the code that after it was created, so if that code accessed this variable, it would catch nil.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question