I have an collection of mealplans and each mealplan has a subcollection of menu items.
The struct for the mealplan looks like this:
protocol MealplanSerializable {
init?(dictionary:[String:Any], mealplanId : String, opened : Bool, menuItems : [MenuItems])
}
struct Mealplan {
var mpName: String
var planType: Int
var menuItems : [MenuItems]
var Dictionary:[String : Any] {
return [
"mpName": mpName,
"planType": planType,
]
}
}
extension Mealplan : MealplanSerializable {
init?(dictionary: [String : Any], mealplanId : String, menuItems : [MenuItems]) {
guard let mpName = dictionary["mpName"] as? String,
let planType = dictionary["planType"] as? Int else { return nil }
self.init(mpName: mpName, planType: planType, mealplanId : mealplanId, menuItems : menuItems)
}
}
And I am querying the meal plan and putting them in the planArray:
db.collection("Meal_Plans").getDocuments {
(querySnapshot, error) in
if error != nil {
//handle error
} else {
self.planArray.append(contentsOf: querySnapshot.documents.compactMap { (queryDocuments) -> Mealplan in Mealplan(dictionary: queryDocuments.data(), mealplanId: queryDocuments.documentID, menuItems: [MenuItems(menuItemName: "", menuItemQuantity: 0)])!})
}
I have to enter an empty menu item to initialize the parent meal plan as you can see in the line above.
So this works, but where I run into a problem is when I need to add the menu items from the subcollection as a nested array within the planArray.
So once I obtain the documentId, I query the DB to get the menu items:
if self.planArray.count >= 1 {
for planIndex in 0...self.planArray.count - 1 {
self.db.collection("Meal_Plans").document(self.planArray[planIndex].mealplanId).collection("Menu_Items").getDocuments { (menuSnapshot, menuError) in
if menuError != nil {
// handle error
} else {
self.planArray[planIndex].menuItems.append(contentsOf: (menuSnapshot?.documents.compactMap { (menuQueryDocuments) -> MenuItems in MenuItems(dictionary: menuQueryDocuments.data())!})!)
}
The struct for the menu items is as follows:
protocol MenuItemsSerializable {
init?(dictionary:[String:Any])
}
struct MenuItems {
var menuItemName: String
var menuItemQuantity: Int
var Dictionary:[String : Any] {
return [
"menuItemName": menuItemName,
"menuItemQuantity": menuItemQuantity
]
}
}
extension MenuItems : MenuItemsSerializable {
init?(dictionary: [String : Any]) {
guard let menuItemName = dictionary["menuItemName"] as? String,
let menuItemQuantity = dictionary["menuItemQuantity"] as? Int
else { return nil }
self.init(menuItemName: menuItemName, menuItemQuantity: menuItemQuantity)
}
}
I have no idea why but this is the error I am getting: