2

I have a Meal structure in my SwiftUI project

struct Meal: Identifiable, Codable, Equatable {
    var id = UUID().uuidString
    var name: String
    var time: String
    var type: String
    var recommendation: Bool    
}

I also have the ContentViewModel class

class ContentViewModel: ObservableObject {
        
    init() {
        
        let allItemsInit = Bundle.main.decode([Meal].self, from: "menu.json")
        self.allItems = allItemsInit
        
        self.recomendationItems = allItemsInit.filter {$0.recommendation == true}
     }
    
    @Published var allItems: [Meal] = []
    @Published var recomendationItems: [Meal] = []
}

Is it a correct approach that I just assign certain elements to the new array of recomendationItems, thereby duplicating them.

recomendationItems - just example, there will be a large number of such subarrays.

1 Answers1

2

You don't need "subarrays" -- your View will get updated whenever allItems changes, so you can use other computed properties to provide the subarrays rather than making them actual separate containers.

For example:

class ContentViewModel: ObservableObject {
        
    init() {        
        self.allItems = Bundle.main.decode([Meal].self, from: "menu.json")
     }
    
    @Published var allItems: [Meal] = []

    var recommendedItems: [Meal] {
      return allItems.filter {$0.recommendation == true}
    }
}
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • Thanks. But what if for example I need 3 arrays of breakfast, lunch and dinner for seven days a week? This results in 21 arrays. Making 21 class fields is probably not the best idea. – Данил May 04 '21 at 23:05
  • Why not make a function that takes those parameters and filters based on them. Something like `func recommendations(meal: MealTime, dayOfWeek: DayOfWeek) -> [Meal]`? I was just following the example you put in your question, but you can definitely filter over more properties. – jnpdx May 04 '21 at 23:10
  • Is it normal if the Meal structure will have an additional 21 fields? struct Meal: Identifiable, Codable, Equatable { var id = UUID().uuidString var name: String var time: String var type: String var recommendation: Bool var mondayBreakfast: Bool var mondayLunch: Bool var mondayDinner: Bool ... } – Данил May 04 '21 at 23:37
  • It looks like your code got cut off there, but that looks like a questionable way to structure the data to me -- you can probably be more efficient with it. But, yes, if you have 21 fields, you would have to filter differently over them. – jnpdx May 04 '21 at 23:47