0

I want wo get value and return,but always return null,so i print the result

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)")
}

At @1 I can get the data,but can't get data At @2 how can i return the value temp

struct WordStruct {
    var word: String?
    var phonetic:String?
    var explains = [String]()
}

1 Answers1

0

Alamofire requests are asynchronous by default. So when you call Alamofire.request the runtime returns immediately before calling your response block. In order to retrieve the WordStruct you'll need to add a completion block to your Getex method.

func Getex(word :String, completion: (WordStruct)->())

Then in your request completion block where you print @1 instead call

//@1print("\(temp)")
completion(temp)

Wherever you are calling Getex, you'll need to pass a completion block similar to how you do with Alamofire.request. For example:

Getex("Test") { word in
     print(word)
}
atreat
  • 4,243
  • 1
  • 30
  • 34
  • thanks very much. http://stackoverflow.com/questions/27390656/how-to-return-value-from-alamofire i read this but not understand after read your answer,i understand how to use – GeorgeYuen Nov 27 '15 at 15:47