向闭包添加返回值 [英] Add a return value to a closure

查看:103
本文介绍了向闭包添加返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对关闭不是很熟悉。我正在使用此功能从远程服务器下载JSON文件

I'm not very familiar with closure. I'm using this function to download a JSON file from a remote server

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文件时返回JSON文件?还是因为异步加载而无法就绪而无法实现?想要我尝试做的事情是这样的:

Is it possible to make the function requestJson() return the JSON file when its loaded? Or it's not possible because it's loaded asynchronously and could not be ready? Want I'm trying to do is something like following:

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


推荐答案

您可以给函数params加上@转义c allback返回数组或您需要的任何内容;

You can give the function params an @escaping callback returning an array or whatever you need;

针对网络请求的示例;

An example of this for a network request;

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

然后称它为可以执行以下操作;

Then to call it you could do something like this;

override func viewDidLoad() {
    getGenres {
        genres in
        print("View Controller: \(genres)")     
    }
}

这篇关于向闭包添加返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆