swift - 使用转义闭包值

标签 swift

用它来填充我的完整 fullJsonData 数组 我想在关闭后继续发挥值(value)。

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错误,调用结果未使用,但产生'[fullJsonData]' 2)然后我尝试在这样的项目中使用它:

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

也有错误:无法将类型“()”的值分配给类型“[fullJsonData]”

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

最佳答案

您应该更改完成处理程序的签名:

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 因为您实际上返回的是一个数组。

关于swift - 使用转义闭包值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44871190/

相关文章:

ios - 自定义栏按钮项目无法正确检测触摸

ios - 你如何获得特定设备的当前位置?

ios - 加载表格 View 时应用程序崩溃并出现错误 "Invalid update: invalid number of sections."

ios - 快速添加范围栏

ios - 如何在 swift 中从十六进制值创建 NSData

ios - 更改 UIImageView 位置的问题

swift - 在 iPad 上的 SwiftUI 中呈现 ActionSheet

json - 如何在 Swift 4 中解码以整数作为键的 JSON?

swift - Alamofire 将应用程序 API 放在 url 的开头而不是结尾

ios - CoreData 使用 NSPredicate 在 NSDate 上有条件地获取(swift)