0

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]'

erikvm
  • 858
  • 10
  • 30
  • Decoding is fine, I just don't know how to put the response from my api into a @Published variable. `DispatchQueue.main.async {self.searchResults = response}` What should the `searchResults` dictionary look like so to say – erikvm Oct 01 '21 at 09:31
  • Where is a guy named 'Verse'? – El Tomato Oct 01 '21 at 10:26
  • A JSON value in Swift 3+ is never `AnyObject` (reference type), it's `Any`. And `JSONDecoder` decodes JSON into **structs**. That's what the error says. If you want a dictionary use `JSONSerialization`. – vadian Oct 01 '21 at 10:42
  • How does Swift know what to decode with `var searchResults: [Verse] = []`? Will it assume I want to decode the `results` array? – erikvm Oct 02 '21 at 18:14

1 Answers1

0

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

var searchResults : SearchResults?
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Mohan
  • 41
  • 2