关于在SwiftUI
中符合Identifiable
,我有一个小问题。
在某些情况下,我们需要有一个给定的类型MyType来符合Identifiable
。
但我面临的情况是,需要[MyType](MyType的数组(来符合Identifiable
。
我的MyType已经符合Identifiable
。我应该怎么做才能使[MyType]也符合Identifiable
?
我建议在结构中嵌入[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
...
}
}
}
您可以编写一个扩展以使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
。