issues with conformance to Identifiable with id: Optional<UUID>

260 Views Asked by At

I want to make my custom list in SwiftUI. I tried to mimic this List’s initializer:

public init<Data, RowContent>(
    _ data: Data, 
    selection: Binding<SelectionValue?>?, 
    @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent
) where 
    Content == ForEach<Data, Data.Element.ID, RowContent>, 
    Data: RandomAccessCollection, 
    RowContent: View, 
    Data.Element: Identifiable

I implemented my own List that way:

struct CustomList<Data: RandomAccessCollection,
                  Selection: Identifiable,
                  Content: View>: View where Data.Element: Identifiable {
    
    @Binding var selection: Selection?
    let content: Content
    
    init<RowContent>(
        _ data: Data,
        selection: Binding<Selection?>?,
        @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent
    ) where
        Content == ForEach<Data, Data.Element.ID, RowContent>,
        Data: RandomAccessCollection,
        RowContent: View,
        Data.Element: Identifiable {
            self._selection = selection ?? .constant(nil)
            self.content = ForEach(data, content: rowContent)
        }
    
    var body: some View {...}
}

I used list with data, defined as

@FetchedResults(…) var myData: FetchedResults<MyData>

MyData declaration:

class MyData: NSManagedObject {
    @NSManaged public var id: UUID?
    …
}

extension MyData: Identifiable { }

It seems, like everything is fine, but when I try to change List to CustomList, code does not compile.

List(myData, selection: $selectedID) { data in // Works fine
    MyDataDetail(data: data, selection: $selectedID)
}

CustomList(myData, selection: $selectedID) { data in // ERROR: Generic struct 'CustomList' requires that 'MyData' (aka 'Optional<UUID>') conform to 'Identifiable'
    MyDataDetail(data: data, selection: $selectedID)
}

What should be changed in CustomList declaration, so it will be able to replace List?

1

There are 1 best solutions below

0
On

So, after some time working on this issue, I’ve found out that issue as not in ForEach, but in requirement of Selection to conform to Identifiable protocol

I just changed

struct CustomList<Data: RandomAccessCollection,
                  Selection: Identifiable,
                  Content: View>: View where Data.Element: Identifiable {…

to

struct CustomList<Data: RandomAccessCollection,
                  Selection,
                  Content: View>: View where Data.Element: Identifiable {…