1

This is so basic, I'm a little embarrassed to ask, but... I'm retrieving some JSON from my server into these structs:

struct CategoryInfo: Codable {
    var categoriesResult: [CategoryDetail]
}

struct CategoryDetail: Codable{
    var categoryName: String
    var categoryDescription: String
    var categorySortOrder: Int
    var categoryId: String
}

And now I want to loop over CategoryDetail for each of the few-dozen occurrences, saving them into CoreData. My current attempt looks like this:

            let decoder = JSONDecoder()
            do {
                let categories = try decoder.decode(CategoryInfo.self, from: data!)
                for category in [CategoryDetail] {
                    //... perform the CoreData storage here
                }

But I get the error that CategoryDetail either doesn't conform to Sequence or to IterateProtocol, but when I try to implement those, the solution appears, frankly, too complicated. It's just an array... shouldn't I be able to loop over it without a lot of hoohaw (using that in a technical sense, of course)?

1 Answer 1

3

Please take a closer look at your structs

You are decoding the CategoryInfo struct

let categoryInfo = try decoder.decode(CategoryInfo.self, from: data!)

and the categories are in the categoriesResult member

for category in categoryInfo.categoriesResult {
    //... perform the CoreData storage here
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, vadian. I went for a walk and thought through what I was doing wrong - which is exactly as you say.

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.