【发布时间】:2015-10-30 23:15:46
【问题描述】:
我是 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
【问题讨论】:
-
闭包的全部意义在于闭包内的语句异步完成。这意味着当您尝试在其外部打印 dict 时,关闭尚未完成。这意味着你想用 dict 做的事情应该在闭包中完成。
-
没错,@SwiftRabbit 是对的。
标签: ios xcode swift scope closures