关于是否符合Identifiable in SwiftUI,我有一个小问题。
在某些情况下,我们需要有一个给定类型的MyType来符合Identifiable。
但我所面临的情况是,我需要MyType与Identifiable保持一致。
我已经让MyType和Identifiable保持一致了。我应该怎么做才能使MyType符合Identifiable
发布于 2021-06-21 02:33:32
我建议将[MyType]嵌入到结构中,然后让结构符合Identifiable。就像这样:
struct MyType: Identifiable {
let id = UUID()
}
struct Container: Identifiable {
let id = UUID()
var myTypes = [MyType]()
}用法:
struct ContentView: View {
let containers = [
Container(myTypes: [
MyType(),
MyType()
]),
Container(myTypes: [
MyType(),
MyType(),
MyType()
])
]
var body: some View {
/// no need for `id: \.self`
ForEach(containers) { container in
...
}
}
}发布于 2021-06-21 12:56:53
您可以编写一个扩展来使Array与Identifiable相一致。
因为扩展不能包含存储的属性,也因为“相同”的两个数组也具有相同的id,所以需要根据数组的内容计算id。
这里最简单的方法是,如果您可以使您的类型符合Hashable
extension MyType: Hashable {}这也使[MyType]符合Hashable,而且由于id可以是任何Hashable,所以可以使用数组本身作为自己的id。
extension Array: Identifiable where Element: Hashable {
public var id: Self { self }
}或者,如果你愿意的话,id可以是Int
extension Array: Identifiable where Element: Hashable {
public var id: Int { self.hashValue }
}当然,您可以只为您自己的类型where Element == MyType执行此操作,但是该类型需要是public。
https://stackoverflow.com/questions/68061637
复制相似问题