Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encoding a dictionary with arrays as values #48

Open
niazoff opened this issue Jun 25, 2018 · 4 comments
Open

Encoding a dictionary with arrays as values #48

niazoff opened this issue Jun 25, 2018 · 4 comments

Comments

@niazoff
Copy link

niazoff commented Jun 25, 2018

Hi, I'm trying to encode a model called Order that has a property called foods that's a dictionary with arrays as values: [FoodType : [AnyFood]]. The keys, FoodType, are enum values with String as their raw value. FoodType also conforms to Codable. When I encode an Order object though with FirebaseEncoder().encode(order) and then setValue(orderData), I get something weird in my Firebase Realtime Database. What I would expect is a child whose path would be /order/foods/salad with enumerated children for each value of the AnyFood array. What happens though is this:

database screenshot

It makes a child /foods with the first item in the foods dictionary has its key 'salad' as /0 and the array value for salad as /1 with the enumerated children as the array's values. How can I encode order in such a way where the value for the path /order/foods/salad/0 would be the first item in the salad key value's array. And then when I would have a coffee key it would map to /order/foods/coffee? (The FoodType keys should be children keys themselves in the database with there children being the values in the [AnyFood] array)

@alickbass
Copy link
Owner

That is the way Codable works when they key in the dictionary is enum. That is a swift's limitation for now. You will have to map it to [String: [AnyFood]] yourself. For more background refer to this page

@niazoff
Copy link
Author

niazoff commented Jun 25, 2018

Oh wow thanks! Do you know if this is fixed in Swift 4.2?

@niazoff
Copy link
Author

niazoff commented Jun 25, 2018

Also would it decode back the proper way when doing so using FirebaseDecoder?

@alickbass
Copy link
Owner

So the results you got were expected. You need to manually map [FoodType : [AnyFood]] to [String: [AnyFood]] in func encode(to encoder: Encoder) throws and the [String: [AnyFood]] to [FoodType : [AnyFood]] in init(from decoder: Decoder) throws. It will not work automatically

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants