Home > Software design >  How to decode a dictionary with a nested array inside?
How to decode a dictionary with a nested array inside?

Time:10-03

I'm fetching some data from an endpoint, and the response looks like this:

{
    "count": 29772,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 29,
            "book_name": "Book title",
            "book_id": 70,
            "chapter_number": 1,
            "verse": "Text",
            "verse_number": 20,
            "chapter": 96
        },
        {
            "id": 30,
            "book_name": "Book Title",
            "book_id": 70,
            "chapter_number": 1,
            "verse": "Lorem ipsum",
            "verse_number": 21,
            "chapter": 96
        }
    ]
}

The struct looks fine:

struct SearchResults: Decodable {
    let count: Int
    let next: String?
    let previous: String?
    let results: [Verse]
    
}

However, how do I initialize this dictionary with a nested array? I tried something like

// here is the issue - what should the searchResults structure look like?
// to properly store the response 
var searchResults: [String: AnyObject] = [String: AnyObject]()

...
 let response = try JSONDecoder().decode(SearchResults.self, from: safeData)
DispatchQueue.main.async {
 self.searchResults = response // error here
}

But get the error message Cannot assign value of type 'SearchResults' to type '[String : AnyObject]'

CodePudding user response:

Change the type of searchResults from [String: AnyObject] to 'SearchResults'

var searchResults : SearchResults?
  • Related