我想得到值并返回,但总是返回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获取数据 我怎样才能返回值temp
struct WordStruct {
var word: String?
var phonetic:String?
var explains = [String]()
}
答案 0 :(得分:0)
默认情况下,Alamofire请求是异步的。因此,当您调用Alamofire.request
时,运行时会在调用响应块之前立即返回。要检索WordStruct,您需要在Getex
方法中添加完成块。
func Getex(word :String, completion: (WordStruct)->())
然后在您的请求完成块中打印@ 1而不是调用
//@1print("\(temp)")
completion(temp)
无论您何时致电Getex
,您都需要传递类似于Alamofire.request的完成方式。例如:
Getex("Test") { word in
print(word)
}