默认情况下,Alamofire请求是异步的。因此,当您调用
我想得到值并返回,但总是返回null,所以我打印结果
func Getex(word :String){
var temp = WordStruct()
let url = "http://fanyi.youdao.com/openapi.do?keyfrom=hfutedu&key=842883705&type=data&doctype=json&version=1.1&q="+word
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
temp.word = word
temp.phonetic = json["basic"]["phonetic"].stringValue
for (_,val) in json["basic"]["explains"]{
temp.explains.append(val.string!)
}
//@1print("(temp)")
}
case .Failure(let error):
print(error)
}
}
//@2 print("(temp)")
}
在@1我可以获取数据,但在@2无法获取数据我如何返回的温度值
struct WordStruct {
var word: String?
var phonetic:String?
var explains = [String]()
}
Alamofire.request
时,运行时会在调用响应块之前立即返回。为了检索WordStruct,您需要在Getex
方法中添加一个完成块。
func Getex(word :String, completion: (WordStruct)->())
然后在您的请求完成块中,打印@1,而不是调用
//@1print("(temp)")
completion(temp)
无论您在哪里调用Getex
,都需要通过一个类似于Alamofire.request的完成块。例如:
Getex("Test") { word in
print(word)
}