Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error Generic parameter 'ID' could not be inferred with DatePicker

Tags:

swiftui

I have a couple of DatePickers in a view with the following code. Each DatePicker presents a digit, so "3" or "5". So for "3456" I have 4 DatePickers that can be changed individually.

struct DigitPicker: View {

    var digitName: String
    @Binding var digit: Int

    var body: some View {
        VStack {
            Picker(selection: $digit, label: Text(digitName)) {
                ForEach(0 ... 9) {
                    Text("\($0)").tag($0)
                }
            }.frame(width: 60, height: 110).clipped()
        }
    }
}

I get an error "Generic parameter 'ID' could not be inferred". So I guess the reason is that $digit must conform to Identifiable(). But how do I do that???

like image 329
arakweker Avatar asked Sep 05 '19 22:09

arakweker


1 Answers

The compiler is resolving the ForEach using this extension:

extension ForEach where Content : View {

    /// Creates an instance that uniquely identifies views across updates based
    /// on the `id` key path to a property on an underlying data element.
    ///
    /// It's important that the ID of a data element does not change unless the
    /// data element is considered to have been replaced with a new data
    /// element with a new identity. If the ID of a data element changes, then
    /// the content view generated from that data element will lose any current
    /// state and animations.
    public init(_ data: Data, id: KeyPath<Data.Element, ID>, content: @escaping (Data.Element) -> Content)
}

And, as you can see, it can't infer the second argument of the init method.

You can make the second argument explicit to make the compiler happy.

ForEach(0 ... 9, id: \.self) { // identified by self
   Text("\($0)").tag($0)
}
like image 129
Matteo Pacini Avatar answered Oct 21 '22 05:10

Matteo Pacini