所以我想要返回jsonMeals数据,并在这个函数之外使用它。然而,不管我把json变量放在哪里,我都会得到一个错误。将其更改为let也可以,尽管是不同的。任何洞察力都将不胜感激!
错误:
Constant 'json' used before being initialized // Variable 'json' was never mutated; consider changing to 'let' constant func getApiDetailData(completed: @escaping () -> ()) {
var json: Any?
let urlString = "https://www.themealdb.com/api/json/v1/1/lookup.php?i=\(id)"
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!)
print("\(json)Testing")
DispatchQueue.main.async {
completed()
}
}
catch {
print("Error getting detail JSON data:\(error)")
}
guard let json = json as? [String : Any],
let jsonMeals = json["meals"] as? [String: Any] else {
print("No meals in json \(error?.localizedDescription)")
return
}
print("testing jsonMeals\(jsonMeals)")
}.resume()
}发布于 2022-05-14 23:52:38
尝试类似于下面的示例代码:
func getApiDetailData(completed: @escaping () -> ()) {
// var json: Any? // <-- remove, never used
let urlString = "https://www.themealdb.com/api/json/v1/1/lookup.php?i=\(id)"
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do {
let jsonData = try JSONSerialization.jsonObject(with: data!)
print("\(jsonData) Testing")
guard let json = jsonData as? [String : Any],
let jsonMeals = json["meals"] as? [[String: Any]] else {
print("No meals in json \(error?.localizedDescription)")
completed() // <-- here
return
}
print("testing jsonMeals \(jsonMeals)")
completed() // <-- here
}
catch {
print("Error getting detail JSON data:\(error)")
completed() // <-- here
}
}.resume()
}或者,如果您想返回jsonMeals结果:
func getApiDetailData(completed: @escaping ([[String: Any]]?) -> ()) { // <-- here
// var json: Any? // <-- remove, never used
let urlString = "https://www.themealdb.com/api/json/v1/1/lookup.php?i=\(id)"
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do {
let jsonData = try JSONSerialization.jsonObject(with: data!)
print("\(jsonData) Testing")
guard let json = jsonData as? [String : Any],
let jsonMeals = json["meals"] as? [[String: Any]] else {
print("No meals in json \(error?.localizedDescription)")
completed(nil) // <-- here
return
}
print("testing jsonMeals \(jsonMeals)")
completed(jsonMeals) // <-- here
}
catch {
print("Error getting detail JSON data:\(error)")
completed(nil) // <-- here
}
}.resume()
}https://stackoverflow.com/questions/72244470
复制相似问题