I have a little question about conforming to Identifiable
in SwiftUI
.
There are situations where we are required to have a given type MyType to conform to Identifiable
.
But I am facing a case where I am required to have [MyType] (an array of MyType) to conform to Identifiable
.
I have MyType already conforming to Identifiable
. What should I do to also make [MyType] to conform to Identifiable
?
I suggest embedding [MyType]
in a struct, then having the struct conform to Identifiable
. Something like this:
struct MyType: Identifiable {
let id = UUID()
}
struct Container: Identifiable {
let id = UUID()
var myTypes = [MyType]()
}
Usage:
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
...
}
}
}