Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conforming an array to Identifiable in SwiftUI

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?

like image 958
Michel Avatar asked Oct 20 '25 15:10

Michel


1 Answers

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
            ...
        }
    }
}
like image 64
aheze Avatar answered Oct 23 '25 04:10

aheze