0

I have the following model:

struct Book: Codable, Identifiable {
    var id: Int
    var title: String
    var author: String
}

struct BookWrapper: Codable {
    var books: [Book]

}

and JSON:

{
  "books": [
    {
        "id":     1,
        "title":  "Nineteen Eighty-Four: A Novel",
        "author": "George Orwell"
    }, {
        "id":     2,
        "title":  "Animal Farm",
        "author": "George Orwell"
    }
  ],
  "errMsg": null
}

I'm trying to grab data using Combine, but cannot find a way how to go around that books array. In case of flat data I would use following:

func fetchBooks() {
        URLSession.shared.dataTaskPublisher(for: url)
            .map{ $0.data }
            .decode(type: [Book].self, decoder: JSONDecoder())
            .replaceError(with: [])
            .eraseToAnyPublisher()
            .receive(on: DispatchQueue.main)
            .assign(to: &$books)
    }   

I tried to use BookWrapper.self, but it doesn't make sense. Is there any elegant way how to solve it?

1
  • Unrelated but eraseToAnyPublisher() makes no sense in this context (no return value) Commented Aug 30, 2021 at 17:57

1 Answer 1

1

You can just map the books property of BooksWrapper before it gets to your assign:

func fetchBooks() {
    URLSession.shared.dataTaskPublisher(for: url)
        .map{ $0.data }
        .decode(type: BookWrapper.self, decoder: JSONDecoder())
        .replaceError(with: BookWrapper(books: [])) //<-- Here
        .map { $0.books }  //<-- Here
        .receive(on: DispatchQueue.main)
        .assign(to: &$books)
}
Sign up to request clarification or add additional context in comments.

2 Comments

It certainly works, but I have no idea what's going on there. Could you point me to any doc which can explain what you did?
The only significant thing added is the map function — you could look at the documentation for it. It’s a good thing to get familiar with if using combine. It takes an input and transforms it to a different output. In this case the input is the BooksWrapper and the output is just the books property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.