alickbass/CodableFirebase

Encoding a dictionary with arrays as values

niazoff opened this issue · 4 comments

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)

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

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

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

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