-1

I am trying to figure out how to return a value from inside a nested function to its parent function. The code that I am working with is:

func findObjectsInBackgroundFromLocalDataStoreIfPossible (query: PFQuery, toCallUponCompletion: () -> ()) -> [PFObject]{
    var response = [PFObject]()
    let queryCopy = query.copy() as! PFQuery
    queryCopy.fromLocalDatastore()
    queryCopy.findObjectsInBackgroundWithBlock{
        (objects: [AnyObject]?, error: NSError?) -> Void in
        if error == nil{
            if objects?.count == 0{
                query.findObjectsInBackgroundWithBlock{
                    (objects2: [AnyObject]?, error: NSError?) -> Void in
                    if error == nil{
                        response = objects2 as! [PFObject]
                    }
                }
            }
            else{
                response = objects as! [PFObject]
            }
        }
        toCallUponCompletion()
    }
}

I need to return the response from inside the function because it can return only once the query has finished, but if I try to do this, the compiler complains that I cannot do this because the return type of the nested function is Void. Is there Swift syntax that allows you to return a value directly to the "parent" function from inside a nested function?

Thanks. Any help is greatly appreciated.

Acoop
  • 2,586
  • 2
  • 23
  • 39

1 Answers1

1

You misunderstand how async calls with completion blocks/closures work.

You can't return a result in your function because at the time the function returns, the result doesn't exist yet.

The function findObjectsInBackgroundFromLocalDataStoreIfPossible takes a closure (a block of code) as a parameter. It returns immediately, before the background network request has even been sent, much less processed.

You then forget about the background job and wait. Once the background task has completed, it calls your closure.

Duncan C
  • 128,072
  • 22
  • 173
  • 272