Looping through a multidimensional array in swift

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?

You cannot, because this is not an array.

Allow me to reproduce your two structure definitions again, reformatting Todo to make its definition a bit clearer:

struct Todolist: Codable {
    let todo: [Todo]
}

struct Todo: Codable {
    let id: String
    let title: String
    let done: String
}

When you decode your JSON as Todolist you get back a single Todolist object containing one array of Todo.

Your for (index, list) in response.todo.enumerated() line therefore produces two variables: index, of type Int, and list, of type Todo. The key here is that Todo is not an array, and does not contain an array. It's an object with 3 properties, each one a String.

So to get the elements, you do this:

for (index, list) in response.todo.enumerated() {
    print(list.id)
    print(list.title)
    print(list.done)
}
4 Likes

works likes a charm thanks!

Terms of Service

Privacy Policy

Cookie Policy