slimboy slimboy - 4 months ago 13
Swift Question

Can't access value outside of completion handler

The following code gives me an error as 'return self.myID' should be at the last curly bracket. Although if I do that, it will claim self.myID as an unresolved identifier since it is outside of the closure. How can I make it so that I can access self.myID outside of the completion handler and place the return value.



func chatPartnerId() -> String? {
nextrequest.startWithCompletionHandler { (connection: FBSDKGraphRequestConnection! , result: AnyObject!, error: NSError!) -> Void in
self.myID = result["id"] as! String
return self.myID

}
}




Answer

Instead of returning a String use a completion handler:

func chatPartnerId(completion: (result: AnyObject?, error: NSError?)->()) {
        nextrequest.startWithCompletionHandler { (connection: FBSDKGraphRequestConnection! , result: AnyObject!, error: NSError!) -> Void in
            if((error) != nil){
               completion(result:nil,error:error)
            }
            else{
                self.myID = result["id"] as! String
                completion(result:self.myID, error:nil)
            }


        }
    }

Call it as

 chatPartnerId() { (result,error) -> Void in
       if let error = error{
          print(error)
       }
       if result != nil {
           print(result)

       }
    }