簡體   English   中英

如何訪問Swift中閉包內的變量?

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

我是Swift的新手,我正試圖從這個函數中得到結果。 我不知道如何訪問閉包內部的變量,該變量從閉包外部傳遞給sendAsynchronousRequest函數。 我已經閱讀了Apple Swift指南中有關閉包的章節,我沒有找到答案,而且我沒有在StackOverflow上找到一個有幫助的答案。 我不能將'json'變量的值賦給'dict'變量,並在閉包之外使用該棒。

    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
        print(dict) // prints the data
    })
    print(dict) // prints nil
var dict: NSDictionary! // Declared in the main thread

然后異步完成閉包,因此主線程不會等待它,所以

println(dict)

在閉包實際完成之前調用。 如果你想使用dict完成另一個函數,那么你需要從閉包中調用該函數,如果你願意,可以將它移動到主線程中,如果你要影響UI,你會這樣做。

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
    //dispatch_async(dispatch_get_main_queue()) { //uncomment for main thread
        self.myFunction(dict!)
    //} //uncomment for main thread
})

func myFunction(dictionary: NSDictionary) {
    println(dictionary)
}

您正在調用異步函數並打印act而無需等待它完成。 換句話說,當調用print(dict) ,函數沒有完成執行(因此dictnil

嘗試類似的東西

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

並將您的JSON邏輯放在doSomethingWithJSON函數中:

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

這可確保您的邏輯僅在URL請求完成后執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM