Ios 如何访问Swift中闭包内部的变量?
我是Swift新手,我正在尝试从这个函数中得到结果。我不知道如何访问从闭包外部传递给sendAsynchronousRequest函数的闭包内部的变量。我已经阅读了Apple Swift指南中关于闭包的章节,但我没有找到答案,也没有找到关于StackOverflow的答案。我无法将'json'变量的值赋给'dict'变量,并将其粘贴到闭包之外Ios 如何访问Swift中闭包内部的变量?,ios,xcode,swift,scope,closures,Ios,Xcode,Swift,Scope,Closures,我是Swift新手,我正在尝试从这个函数中得到结果。我不知道如何访问从闭包外部传递给sendAsynchronousRequest函数的闭包内部的变量。我已经阅读了Apple Swift指南中关于闭包的章节,但我没有找到答案,也没有找到关于StackOverflow的答案。我无法将'json'变量的值赋给'dict'变量,并将其粘贴到闭包之外 var dict: NSDictionary! NSURLConnection.sendAsynchronousRequest(reque
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
然后异步完成闭包,这样主线程就不会等待它,所以
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)
时,函数尚未完成执行(因此dict
为nil
)
试试像这样的东西
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请求完成后才执行逻辑。闭包的关键在于闭包内的语句异步完成。这意味着当您试图在封口外打印dict时,封口尚未完成。这意味着你想用dict做的事情应该在闭包中完成。没错,@SwiftRabbit是对的。谢谢,但是当我尝试使用主线程时,我得到了“不能用类型为“(NSDictionary)”的参数列表调用“myFunction”。已经修改了代码以修复该错误,dict需要在使用!编辑:获取错误时,无法使用类型为“(dispatch_queue_t!,()->Void)”的参数列表调用“dispatch_async”。请将您的代码发送给我,我需要查看它所处的上下文类型,以及它是否在一个函数中实现。几天前,etcI已找出问题的根源。这真的是一个很简单的错误。我做了一个静态函数,但忘记了我做了静态函数,这就是导致所有问题的原因。
void doSomethingWithJSON(dict: NSDictionary) {
// Logic here
}