为什么不能将JSON响应分配给变量以供以后使用?

时间:2019-07-07 12:08:22

标签: swift xcode

我为数组的json响应分配了一个变量。问题是我以后无法访问它,因为它说它没有下标。我必须访问原始变量(实际上是常量)才能从响应中获取所需的信息。希望代码会更清晰。

let data = (try? Data(contentsOf: URL(fileURLWithPath: path!), options: .mappedIfSafe))
        do {
            // data we are getting from network request
            let decoder = JSONDecoder()
            let response = try decoder.decode(Recipes.self, from: data!)

            let recipes = response.recipe

for (index, recipes) in recipes.enumerated(){
        //This prints the info ok!
                print(response.recipe[index].name)
                print(response.recipe[index].nutrients.protein)
                print(response.recipe[index].steps[2])

//This does't and it says it has no subscripts!
                print(recipes[index].name)
                print(recipes[index].nutrients.protein)
                print(recipes[index].steps[2])
}
  } catch { print(error) }

错误:“食谱”类型的值没有下标

1 个答案:

答案 0 :(得分:1)

首先,请始终以单数形式在for循环中命名一个项目,以免造成混淆和错误(循环元素变量的名称隐藏了数组的 same 名称变量)。

for (index, recipe) in recipes.enumerated() { ...

然后一行

print(recipes[index].name)

将起作用。但是,您可以编写更简单的

print(recipe.name)