无法使用 DatePicker 推断错误通用参数 'ID'

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

我在视图中有几个 DatePickers,代码如下。每个 DatePicker 都显示一个数字,如“3”或“5”。所以对于“3456”,我有 4 个可以单独更改的 DatePickers。

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("\([=11=])").tag([=11=])
                }
            }.frame(width: 60, height: 110).clipped()
        }
    }
}

我收到一个错误 "Generic parameter 'ID' could not be inferred"。所以我猜原因是$digit必须符合Identifiable()。但是我该怎么做呢???

编译器正在使用此扩展解析 ForEach

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

而且,如您所见,它无法推断出 init 方法的第二个参数。

您可以将第二个参数显式化以使编译器满意。

ForEach(0 ... 9, id: \.self) { // identified by self
   Text("\([=11=])").tag([=11=])
}