-2

The method fails to return a value got from a GET request where variable res can be printed in the task section, but fails to return it in the end.

func lookUpTheWord(word:String) -> NSDictionary {
    var res = NSDictionary()
    let urlString = "https://wordsapiv1.p.mashape.com/words/" + word
    if let url = NSURL(string:urlString) {
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "GET"
        request.addValue("this is a key", forHTTPHeaderField: "X-Mashape-Key")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            if error != nil {
                print("\(error)")
                return
            }
            res = self.toJson(data!)
            print(res) //it works here
        }
        task.resume()
    }
    return res //res becomes nil
}
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
Joey Zhang
  • 363
  • 6
  • 18
  • 1
    Possible duplicate of [Swift: How do I return a value within an asynchronous urlsession function?](http://stackoverflow.com/questions/27081062/swift-how-do-i-return-a-value-within-an-asynchronous-urlsession-function) – Kurt Revis May 22 '16 at 01:45

1 Answers1

1

That is because you're returning the variable res before it has been assigned. You'll notice that the res that isn't nil is printed after the one that is after it. This is because the HTTP request doesn't happen instantly - code after it is executed before it is finished, therefore it is called "asynchronous".

If you want to use the variable acquired in the HTTP request, use a closure as a parameter in your function and call it when the request is finished. Example:

func lookUpTheWord(word:String, completion: (NSDictionary->Void)) {
    var res = NSDictionary()
    let urlString = "https://wordsapiv1.p.mashape.com/words/" + word
    if let url = NSURL(string:urlString) {
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "GET"
        request.addValue("this is a key", forHTTPHeaderField: "X-Mashape-Key")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            if error != nil {
                res = self.toJson(data!)
                completion(res)
            }
        }
        task.resume()
    }
}

Used like this:

lookUpTheWord("word") { res in
    print(res)
}
brimstone
  • 3,370
  • 3
  • 28
  • 49