使用转义封闭值

时间:2017-07-02 13:13:39

标签: swift

让它填充我的完整fullJsonData数组 我想在关闭后使用价值。

func getNewsAsDic(completionHandler: @escaping ([fullJsonData]) -> [fullJsonData]) {

    let session = URLSession.shared
    let dataTask = session.dataTask(with: requestNewsForToday()) { data, _, error in
        if error == nil {
            if let dic = try? JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
                var dataArray = [fullJsonData]()

                let jdata = dic?["articles"] as! [[String:Any]]

                for item in jdata {

                    let data = fullJsonData(author: item["author"] as? String,
                                            description: item["description"] as? String,
                                            publishedAt: item["publishedAt"] as? String,
                                            title: item["title"] as? String,
                                            url: item["url"] as! String,
                                            imageURL: item["urlToImage"] as? String)

                    print(item["author"] as! String)
                    print(item["description"] as! String)
                    print(item["title"] as! String)
                    print(item["urlToImage"] as! String)
                    print(item["url"] as! String)
                    print(item["urlToImage"] as! String)
                    print(item["publishedAt"] as! String)

                    dataArray.append(data)
                }
                completionHandler(dataArray)
                print(jdata.count)
            }
        } else {
            return
        }
    }
    dataTask.resume()
}

问题是: 1)xcode错误,Result of call is unused, but produces '[fullJsonData]' 2)然后我试图在这样的项目中使用它:

var dataArray = [fullJsonData]()
        dataArray = NetworkManager.shared.getNewsAsDic(completionHandler: { dict in
            return dict
        })

也有错误:Cannot assign value of type '()' to type '[fullJsonData]'

从闭包中获取和使用值是真的吗?

2 个答案:

答案 0 :(得分:0)

您应该从以下位置更改完成处理程序的签名:

func getNewsAsDic(completionHandler: @escaping ([fullJsonData]) -> [fullJsonData]) {

到:

func getNewsAsDic(completionHandler: @escaping ([fullJsonData]) -> Void) {

然后将您的电话改为:

NetworkManager.shared.getNewsAsDic(completionHandler: { myArray in
    // Do whatever you want with myArray here
})

此外,您应该重命名getNewsAsDic,因为您确实正在返回一个数组。

答案 1 :(得分:0)

似乎你必须使用

var dataArray: [fullJsonData] = []代替您的代码。