我有一段代码,其中可选项已初始化,然后在函数中为其分配值,但在解包时为nill
?Swift变量值和函数
var datastring: String?
Alamofire.request(.POST, "https://example.url/request", parameters: parameters) .response { request, response, data, error in
datastring = NSString(data: data!, encoding:NSUTF8StringEncoding) as! String // there is data in here
// textView.text = datastring! datastring is not nill when here
}
textView.text = datastring! // datastring is nill when here
这不是Alamofire特定的。在使用本地Swift方法时,我遇到了这个问题。我在做什么错,为什么Swift这样工作?
PS。我还在学习:)
编辑:谢谢所有帮助我的人。为了澄清问题,这是一个将变量的值从异步线程传递到主线程的问题。我只是不知道该怎么说。
datastring被设置在回调(异步)内部。同时,主线程继续运行,因此当textView.text设置时,变量中没有任何内容。您需要将您的值传回给另一个回调中的主线程。 – ohiodoug
[Alamofire request up up up nil]的可能重复(http://stackoverflow.com/questions/35372850/alamofire-request-coming-up-nil) – jtbandes
@ohiodoug谢谢你解释这一点。这是我不明白的。 –