我有一段代碼,其中可選項已初始化,然後在函數中爲其分配值,但在解包時爲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謝謝你解釋這一點。這是我不明白的。 –