How do I access variables that are inside closures in Swift?

后端 未结 2 1021
有刺的猬
有刺的猬 2021-01-19 15:05

I\'m new to Swift and I\'m trying to get the result from this function. I don\'t know how to access variables that are inside the closure that is passed to the sendAsynchron

2条回答
  •  孤街浪徒
    2021-01-19 15:43

    You are calling an asynchronous function and printing act without waiting for it to finish. In other words, when print(dict) is called, the function hasn't complete execution(hencedict is nil)

    Try something like

    var dict: NSDictionary!
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response, data, error) in
        var jsonError: NSError?
        let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSDictionary
        dict = json
        doSomethingWithJSON(dict)
    })
    

    and put your JSON logic inside a doSomethingWithJSON function:

    void doSomethingWithJSON(dict: NSDictionary) {
        // Logic here
    }
    

    This ensures that your logic is execute only after the URL request completes.

提交回复
热议问题