I have a FridgeVC
inside which I search for some ingredients and add them to the selectedIngredients
array. For this I use Ingredient
model. and also I have a childVC there. On childVC I have findRecipes button. For now I can search for ingredients and append them to the selectedIngredients
array. Then I want to use a different endpoint of my API and search recipes related to these selected ingredients by using FindByIngredients
model but I fail. I use UICollectionViewDiffableDataSource
for this. When I tap on findRecipes button I want the ingredients to be removed and show the recipes along with their images and titles. The same cell (FridgeVcCell
) I am using for ingredients would also work for this purpose. In the configureDataSource()
function I am configuring the data source for the Ingredient
model.
If I want to reuse the same dataSource for both Ingredient
and FindByIngredients
models, what should I do? How to combine these two models into one?
I tried some things but they didn't work. I asked ChatGPT and it advised to use a protocol named DisplayableItem
and then make both Ingredient
and FindByIngredients
conform to it. But it gives me this following error:
Use of protocol 'DisplayableItem' as a type must be written 'any DisplayableItem'
Some parts of my code are below:
Ingredient model:
struct Ingredient: DisplayableItem, Codable, Hashable {
let name: String
let image: String
var imageURL: String? {
return "https://spoonacular.com/cdn/ingredients_100x100/\(image)"
}
}
FindByIngredients model:
// MARK: - RecipeSearchElement
struct FindByIngredients: DisplayableItem, Codable, Hashable {
let id: Int
let title: String
let image: String
let imageType: String
let usedIngredientCount, missedIngredientCount: Int
let missedIngredients, usedIngredients: [SedIngredient]
//let unusedIngredients: [JSONAny]
let likes: Int
enum CodingKeys: String, CodingKey {
case id, title, image, imageType, usedIngredientCount, missedIngredientCount, missedIngredients, usedIngredients, likes
}
}
// MARK: - SedIngredient
struct SedIngredient: Codable, Hashable {
let id: Int
let amount: Double
let unit, unitLong, unitShort, aisle: String
let name, original, originalName: String
let meta: [String]
let image: String
let extendedName: String?
}
Beginning of my VC. Here I get lots of errors:
import UIKit
protocol DisplayableItem: Hashable {
}
class FridgeVC: UIViewController, UISearchBarDelegate {
enum Section { case main }
let ingredientsVC = IngredientsVC()
var user: User?
private var ingredients = [String]()
var ingredientsArray: [DisplayableItem] = []
var recipesArray: [DisplayableItem] = []
var selectedIngredients: [DisplayableItem] = []
var hasMoreIngredients = true
var page = 1
var isLoadingMoreIngredients = false
var dataSource: UICollectionViewDiffableDataSource<Section, DisplayableItem>!