错误 无法使用日期选取器推断泛型参数'ID'



我在视图中有几个日期选取器,其中包含以下代码。每个日期选取器都显示一个数字,即"3"或"5"。因此,对于"3456",我有 4 个可以单独更改的日期选择器。

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

我收到错误"无法推断通用参数'ID'"。所以我想原因是$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("($0)").tag($0)
}

最新更新