3

I have a List that iterates over an array of protocols and creates a NavigationLink for each protocol, with a label that displays a field of the protocol.

When trying to use the .navigationDestination modifier on the list for the Protocol's data type, I get the following error:

Type 'any SpendCategoryModel' cannot conform to 'Hashable'

My protocol conforms to Hashable and all the implementations of the protocol do as well.

Is it possible to navigate with a generic protocol as the data source?

struct CategoryLookupView: View {
    @ObservedObject var categoryLookupViewModel: CategoryLookupViewModel
    
    var body: some View {
        NavigationStack {
            List {
                Section {
                    ForEach(categoryLookupViewModel.filteredCategories, id: \.name) { spendCategory in
                        NavigationLink(value: spendCategory) {
                            Text(spendCategory.name)
                        }
                    }
                }
            }
            .navigationDestination(for: SpendCategoryModel.self) { spendCategory in
                CardResultView(spendCategory: spendCategory)
            }
        }
    }
}
protocol SpendCategoryModel: Hashable, Codable {
    var name: String { get set }
    func getIds() -> [Int]
}
1
  • 1
    No, you can't. A generic protocol has no data It is just blueprint to be adopted by a class, structure, or enumeration to provide an actual implementation. You have to use an actual implementation here. A protocol has no substance to implement.
    – Yrb
    Jun 25, 2023 at 16:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.