添加一个返回值到闭包

我不是很熟悉closures。 我正在使用此function从远程服务器下载JSON文件

requestJson(){ // Asynchronous Http call to your api url, using NSURLSession: NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://api.site.com/json")!, completionHandler: { (data, response, error) -> Void in // Check if data was received successfully if error == nil && data != nil { do { // Convert NSData to Dictionary where keys are of type String, and values are of any type let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject] // Access specific key with value of type String let str = json["key"] as! String } catch { // Something went wrong } } }).resume() } 

是否有可能使函数requestJson()返回JSON文件加载时? 或者这是不可能的,因为它是asynchronous加载,不能准备好吗? 想要我想要做的是像下面的东西:

 requestJson() -> **[String : AnyObject]**{ // Asynchronous Http call to your api url, using NSURLSession: NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://api.site.com/json")!, completionHandler: { (data, response, error) -> Void in // Check if data was received successfully if error == nil && data != nil { do { // Convert NSData to Dictionary where keys are of type String, and values are of any type let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject] // Access specific key with value of type String **return json** } catch { // Something went wrong } } }).resume() } 

你可以给函数参数@escapingcallback返回一个数组或任何你需要的;

networking请求的一个例子;

 class func getGenres(completionHandler: @escaping (genres: NSArray) -> ()) { ... let task = session.dataTask(with:url) { data, response, error in ... resultsArray = results completionHandler(genres: resultsArray) } ... task.resume() } 

然后打电话给你,你可以做这样的事情;

 override func viewDidLoad() { getGenres { genres in print("View Controller: \(genres)") } } 
 //MARK: Request method to get json class func requestJSON(completion: @escaping (returnModel: String?) -> Void) { //here you write code for calling API } //MARK: Calling function to retrieve return string API.requestJSON(completion: { (string) in //here you can get your string }) 
 func httpGet(request: NSURLRequest!, callback: (NSString, NSString?) -> Void) { var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in if error != nil { callback("", error.localizedDescription) } else { var result = NSString(data: data, encoding: NSASCIIStringEncoding)! callback(result, nil) } } task.resume() } func makeRequest(callback: (NSString) ->Void) -> Void { var request = NSMutableURLRequest(URL: NSURL(string: "http://sample_url")!) var result:NSString = "" httpGet(request){ (data, error) -> Void in if error != nil { result = error! } else { result = data } callback(data) } } 

用法:-

  self.makeRequest(){ (data) -> Void in println("response data:\(data)") }