Post

Replies

Boosts

Views

Activity

custom EnvironmentKey lookup causes compiler error
I receive the following compiler error: Cannot infer key path from context; consider explicitly specifying a root type when I attempt an @Environment(\.foodRepository) lookup in a descendant View. Here's the setup in my App class: import SwiftUI import SwiftData @main struct BulkCutApp: App { private var foodRepository: FoodRepository = /* some code*/ var body: some Scene { WindowGroup { ContentView() .foodRepository(foodRepository) } } } extension View { func foodRepository(_ customValue: FoodRepository) -> some View { environment(\.foodRepository, customValue) } } extension EnvironmentValues { var foodRepository: FoodRepository { get { self[FoodRepositoryKey.self] } set { self[FoodRepositoryKey.self] = newValue } } } struct FoodRepositoryKey: EnvironmentKey { static var defaultValue: FoodRepository = FoodRepository(food:[]) } Nothing special in FoodRepository: @Observable class FoodRepository { var food: [Food] // more code }
0
0
61
5d