Joey Zhang Joey Zhang - 6 months ago 31
Swift Question

my swift app fails to return a dictionary value

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
}

Answer

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