【发布时间】:2020-05-25 11:14:24
【问题描述】:
我正在尝试使用 SwiftyJSON 和 Spoonacular API 来做一些食谱应用程序。
我是一名初级开发人员,因此在遍历 JSON 响应结果时遇到了麻烦。我正在将 SwiftyJSON 与 Alamofire 结合使用。
API 结果如下所示:
"results": [
{
"id": 548450,
"title": "Sweet Potato Kale Pizza with Rosemary & Red Onion",
"image": "https://spoonacular.com/recipeImages/548450-312x231.jpg",
"imageType": "jpg"
},
{
"id": 759293,
"title": "Deep-Dish Skillet Pizza",
"image": "https://spoonacular.com/recipeImages/759293-312x231.jpg",
"imageType": "jpg"
},
我想查看每个配方结果,并获取 ID 和标题。我该怎么做?
通过谷歌搜索,大多数人建议如下:
for (key, subJson) in json {
let id = json["results"][index]["id"].stringValue
let title = json["results"][index]["title"].stringValue
print(id)
print(title)
}
如您所见,我在访问 JSON 响应中的每个索引时遇到了问题。上面的代码似乎遍历了每个键(在本例中,有 4 个,id,title,image 和 imageType),所以它不会遍历每个索引。
当我认为从响应数据创建的 JSON 不是普通数组时,我只是在弄清楚如何迭代每个索引时遇到了麻烦
【问题讨论】:
-
为什么不用codable?
标签: json swift loops alamofire