I am fairly new to swift and got some issues with looping through an array i got from a json file. So i can obtain the individual keys just fine but the amount of items inside my array differs so i need to loop through the content.
Imagine this being my JSON response:
{
"todo": [
{
"id": "31",
"title": "Loftdeur",
"done": "0"
},
{
"id": "32",
"title": "test",
"done": "0"
}, {
"id": "36",
"title": "test",
"done": "0"
}
]
}
My struct
struct Todolist: Codable {
let todo: [Todo]
}struct Todo: Codable {
let id, title, done: String
}
I decode it with the code below:
do {
let decoder = JSONDecoder() let response = try decoder.decode(Todolist.self, from: data!) print(response.todo[1].title) //Output - EMT let size = response.todo.count print(size) for(index, list) in response.todo.enumerated() { print(list) } }
I can print an individual key:
print(response.todo[1].title)
when i print(list) inside my first for loop i get:
Todo(id: "31", title: "Loftdeur", done: "0")
Todo(id: "32", title: "test", done: "0")
Todo(id: "33", title: "test", done: "0")
I thought adding another for loop would do the trick but then i get an error:
for title in list { print("item: \(title)") }
Type 'Todo' does not conform to protocol 'Sequence'
How can i loop through this array and grab each individual key of the array?