我目前正在尝试通过编写可多次使用的通用函数来清理项目上的代码。但是我需要我的函数返回一个数组。我的错误是“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)
}
这很有帮助
关于swift - 使用 json 序列化的 void 函数 swift 4 中出现意外的非 void 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47713167/