swiftswiftui

Array with generically typed element cannot be used in ForEach `Cannot convert value of type '[C]' to expected...`


I am guessing if the error were more helpful this would be obvious but for now this is the code I am trying to get to compile.

struct MultiselectFilterDropdown<C>: View where C : Identifiable, C.ID : Equatable, C.ID : CustomStringConvertible {
    var allItems: [C]

    var body: some View {
        VStack {
            ForEach(allItems) { item in
                Text(item.description)
            }
        }
    }
}

And I don't know why the compiler cannot sort it out. I have seen it say it can't convert to Range<Int> or Binding<C> so I am guessing the complier doesnt even know which initializer of ForEach would be most relevant.


Solution

  • The CustomStringConvertible is missplaced.

    struct MultiselectFilterDropdown<C>: View
        where C : Identifiable & CustomStringConvertible,
                C.ID : Equatable {
        var allItems: [C]
    
        var body: some View {
            VStack {
                ForEach (allItems) { item in
                    Text(item.description)
                }
            }
        }
    }
    

    That Binding error is a tell tale sign of a typo.