[英]SwiftUI - Error - Initializer 'init(_:rowContent:)' requires that 'CustomDataModel' conform to 'Identifiable'
[英]SwiftUI String conform Identifiable seems not correct
我在List
使用一个数组,在List
有一个ForEach
,例如:
struct AView: View {
@State var foo: [String] = ["a", "b", "c"]
var body: some View {
ZStack {
Color.white
List {
ForEach(foo.indices) { index in
Text(foo[index])
}
}
}
}
}
这很好用,然后我想添加一个按钮来插入新项目:
List {
ForEach(foo.indices) { index in
Text(foo[index])
}
}
Button("Add") {
foo.append("foo")
}
}
然后我得到了错误,这显然是:
ForEach<Range<Int>, Int, Text> count (4) != its initial count (3). `ForEach(_:content:)` should only be used for *constant* data. Instead conform data to `Identifiable` or use `ForEach(_:id:content:)` and provide an explicit `id`!
这里提到
Identifiable
或使用ForEach(_:id:content:)
我可以使用ForEach(foo.indices, id:\\.self)
来解决这个问题。
我也想尝试Identifiable
,不要在ForEach
、 ForEach(foo.indices)
使用id:\\.self
。
我为 String 添加了扩展名,例如:
extension String: Identifiable {
public var id: String { self }
}
但还是遇到了同样的问题。 有什么我想念的吗? 谢谢!
编辑
根据评论@New Dev,因为我是字面indices
,所以我添加了对Int
扩展:
extension Int: Identifiable {
public var id: Int { self }
}
仍然不起作用。
ForEach
有多个init
重载。
init(Range<Int>, content: (Int) -> Content)
仅适用于恒定范围 - 因此出现错误。
init(Data, content: (Data.Element) -> Content)
要求Data
符合可Identifiable
元素的RandomAccessCollection
。 这就是你想要使用的。
问题是您的RandomAccessCollection
( Range<Int>
符合的)是Int
元素的集合。
尽管您可以使Int
符合Identifiable
,但这仍然不起作用。 它仍然会使用带有Range<Int>
参数的第一个ForEach.init
,因为方法重载偏好——即Range<Int>
匹配更具体的init
和Range<Int>
参数,而不是匹配不太具体的init
和RandomAccessCollection
。
所以,你的选择是:
id
使用第三个init(Data, id: KeyPath<Data.Element, ID>, content: (Data.Element) -> Content)
。ForEach(foo.indices, id:\.self) { index in
}
Array<Int>
并符合Int: Identifiable
:extension Int: Identifiable { var id: Self { self } }
ForEach(Array(foo.indices)) { index in
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.