我目前正在尝试通过编写可以多次使用的通用函数来清理项目上的代码。但是我需要我的函数返回一个数组。我的错误是“void 函数中出现意外的非 void 返回值”
这是我的代码
func JSONSerialisation(JsonUrl: String) -> NSArray{
let url = URL(string: JsonUrl)
let task = URLSession.shared.dataTask(with: url!) { (data, responce, error) in
if error != nil
{
print("error")
}
else
{
if let content = data
{
do
{
if let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray{
return Json //Error occurs here
}
}
catch
{
}
}
}
}
task.resume()
}
Stack Overflow 上有一些类似的问题,但到目前为止,没有一个能够解决我的问题,因为他们都说添加-> NSArray
.
提前致谢
您无法直接从异步任务返回数据。使用闭包
使用闭包创建一个函数,例如。
func jsonSerialisation(jsonUrl: String, completion block: @escaping ((NSArray) -> ())){
let url = URL(string: JsonUrl)
let task = URLSession.shared.dataTask(with: url!) { (data, responce, error) in
if let e = error{
print(e.localizedDescription)
}
else{
if let content = data{
do {
if let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray{
block(Json)
}
}
catch let error{
print(error.localizedDescription)
}
}
}
}
task.resume()
}
并致电:
jsonSerialisation(jsonUrl: "Your Url") { (json) in
print(json)
}
这很有帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)