How to create subarrays without duplication Swift

Viewed 65

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 Answers

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}
    }
}
Related