我正在尝试解析我的JSON数据,并仅将这些对象附加到符合指定条件的数组中。目前,我已经注释掉了从API获取所有对象并将它们添加到数组中的代码。但是,我想限制它,以便它只为“license_author”键附加“wger.de”值的对象。
但是我在网上收到错误:
if eachExercise["license_author"] == "wger.de"
二进制运算符'=='不能应用于'Any?'类型的操作数和'字符串'。 但是我仍然希望将它保留为Any对象,因为我想从我的API中获取字符串和整数数据。
这是我的parseData()函数的代码:
func parseData() {
fetchedExercise = []
let urlPath = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"
let url = URL(string: urlPath)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Error while parsing JSON")
}
else {
do {
if let data = data,
let fetchedData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any],
let exercises = fetchedData["results"] as? [[String: Any]] {
// WORKING CODE
/*
for eachExercise in exercises
{
let name = eachExercise["name"] as! String
let description = eachExercise["description"] as! String
self.fetchedExercise.append(Exercise(name: name, description: description))
}
*/
// TESTING
for eachExercise in exercises {
if eachExercise["license_author"] == "wger.de" {
let name = eachExercise["name"] as! String
let description = eachExercise["description"] as! String
let id = eachExercise["id"] as! Int
self.fetchedExercise.append(Exercise(name: name, description: description))
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
catch {
print("Error while parsing data.")
}
}
}
task.resume()
}
答案 0 :(得分:0)
您需要将其强制转换为String。
const
答案 1 :(得分:0)
使用where
子句和可选的向下转发Any
到String
for eachExercise in exercises where eachExercise["license_author"] as? String == "wger.de" { ...