用它来填充我的完整 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/